Java Lesson 9: Arrays

3
42

Introduction

As we learned in Lesson 4, variables store a value, such as the number 8, in a named location. Arrays in Java are a very powerful kind of variable because they can hold collections of related primitive types or objects that all have the same name. An index references each entry in the array. Arrays are analogous to the mathematical concept of a matrix. Arrays can be one dimensional or multi-dimensional.

Arrays

Conceptual Diagram

Arrays are easier to conceptualize with a diagram.

Diagram of an array, showing the array name, index positions, and values contained in the array.
Figure 9-1. Diagram of an array.

Properties of an Array

The array has a name, just like any other variable. Each element in the array contains a value of the array type. The individual element in the array must all be of the same type, such as double, int, or String. The above array is of type int, with the values 20, 23, 27, and so on. An index points to a position in the array where an individual element is located. Note that the index is zero-based; i.e., the first element position has an index of 0, the second element position has an index of 1. This is very important to remember, and you won’t be the first person to forget. In Figure 9-1, index position 4 contains the integer number 31.

A one-dimensional array may be thought of as a spreadsheet with only one row, except that the columns are numbered starting at index 0 instead of index 1 or index A.

Declare an Array

An array must be declared before a program accesses elements in the array. As with objects, the new operator is used to allocate an array.

A shorter (and more common) way of declaring an array is to combine the above two statements into one statement.

The above declaration creates an array with 8 elements, with the elements numbered 0 though 7. They are:

Access an Array

Like a variable, a number can be put into an individual element and retrieved later for use in calculations or for display:

You will receive an “Array Index Out Of Bounds Exception” (error) if you try accessing an element that does not exist. This usually happens when you try accessing an element one greater than the size of the array. Using our values array, the statement:

results in the Java VM prematurely exiting the program with an Array Index Out of Bounds Exception:

Assignment Statements

An entire array can be populated with assignment statements to assign a value to each element in the array.

Iterate Through Arrays Using for Loops

A common practice is to iterate through an entire array using a for loop. It can be said that this is what the for loop was made for. An index variable of type int is declared in the for loop and is used to access the next successive element each time through the loop.

Arrays are similarly processed using while and do-while loops.

The length Variable

Java handily provides an instance variable named length for every array that you declare, which contains the size of the array, that is, the maximum number of elements in the array. Simply append .length to the end of the array name.

length is especially useful when iterating through an array. It automatically knows what the maximum index is, and can help prevent the dreaded “Array Index Out Of Bounds Exception.” So, instead of hardcoding the number 8, we can rewrite the example above as:

That way, if you ever change the size of the array you won’t have to search through your program to modify “8” to whatever the new size is.

Declare and Initialize Arrays in One Step

You can declare and initialize an array in one step if you know what values you want to insert into the array. Enclose the comma-separated values inside of curly braces when you declare the array. The following example creates an array with five integers and then displays the array’s contents on the console.

Arrays of Strings and Other Types

Arrays can be made up of any type and work similar to the integer arrays we have created so far. This example creates an array of Strings.

As with int arrays, a String array declaration can be done in one step.

The Enhanced For Loop (for-each)

JDK 5 introduced a new kind of for loop called an Enhanced For Loop, also known as the for-each loop because it successively iterates through an array for each element in the array. The enhanced for loop cycles through a collection of objects in a sequential fashion from start to finish.

The following code uses a traditional for loop to display the elements in the array:

The enhanced for loop eliminates the need to specify a starting and ending value. You can read the following code fragment as, “for each word in the words array, perform the statement(s) in the {code block}.”

The enhanced for loop also works for arrays of other types:

Multi-Dimensional Arrays

As with a mathematical matrix or a spreadsheet, two-dimensional arrays are indexed by rows and columns. Although not as common, arrays can have three, four, or even more dimensions.

A two-dimensional array with rows and columns.
Figure 9.2: Two-dimensional array.

In Java a two-dimensional array is really an array of arrays. Each element of an array is another array. The syntax to declare and process a two-dimensional array is somewhat convoluted but it will become familiar with practice. Note the first and last curly braces which enclose the entire array, and the location of commas and the trailing semi-colon. Also remember we start counting from 0 (not 1), so the following code fragment displays “21“.

Multi-Dimensional Arrays of Strings and Other Types

Multi-dimensional arrays can be made up of other types, including Strings.

Display a Two-Dimensional Array Like a Spreadsheet

Program9a.java takes everything we have learned about arrays to create a two-dimensional array and display it like a spreadsheet:

Execution of Program9a.java, which creates a two-dimensional array and displays it to like a spreadsheet to the user.

One More Example

As a last example in this lesson, let’s write a program which has an array of fruits. The program will process the array and determine the plural equivalent of the fruit. For example, “apple” becomes “apples”, “pear” becomes “pears”, and “cherry” is a special case because “cherry” becomes “cherries” (drop the “y”, and add “ies”). We will use an array of Strings for the fruit names, a for-each loop, and an if statement to check for “cherry”.

Execution of Program9b.java which converts fruit names to their plural equivalent.

Summary

In this lesson we learned about Java’s three looping (iterative) statements, for, while, and do-while, which allow you to control the program’s execution by repetitively executing code blocks depending upon conditions at execution time.

Next Lesson

Next we will move on to Methods.

 

3 COMMENTS

  1. […] The increment operator, “++“, automatically adds 1 and stores the result into the original variable. The statement “x++;” is equivalent to “x = x + 1;“. It is commonly used in for loops and indexing arrays. […]

  2. […] safest way to avoid going beyond an array’s bounds is, as we learned in Java Lesson 9: Arrays, to use the length() method which returns the length of the […]

  3. […] Loops are often used to process arrays. And curiously enough, that is the subject of our next lesson: Arrays. […]

Leave a Reply