The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Accessing Elements

An array is a set of values where each value is identified by an index. You can make an array of ints, doubles, or any other type, but all the values in an array have to have the same type.

Syntactically, arrays types look like other Java types except they are followed by []. For example, int[] is the type "array of integers" and double[] is the type "array of doubles."

You can declare variables with these types in the usual ways:

    int[] count;
    double[] values;

Until you initialize these variables, they are set to null. To create the array itself, use the new command.

    count = new int[4];
    values = new double[size];

The first assignment makes count refer to an array of 4 integers; the second makes values refer to an array of doubles. The number of elements in values depends on size. You can use any integer expression as an array size.

The following figure shows how arrays are represented in state diagrams:

The large numbers inside the boxes are the elements of the array. The small numbers outside the boxes are the indices used to identify each box. When you allocate a new array, the elements are initialized to zero.

To store values in the array, use the [] operator. For example count[0] refers to the "zeroeth" element of the array, and count[1] refers to the "oneth" element. You can use the [] operator anywhere in an expression:

    count[0] = 7;
    count[1] = count[0] * 2;
    count[3] -= 60;

All of these are legal assignment statements. Here is the effect of this code fragment:

By now you should have noticed that the four elements of this array are numbered from 0 to 3, which means that there is no element with the index 4. This should sound familiar, since we saw the same thing with String indices. Nevertheless, it is a common error to go beyond the bounds of an array, which will cause an ArrayOutOfBoundsException. As with all exceptions, you get an error message and the program quits.

You can use any expression as an index, as long as it has type int. One of the most common ways to index an array is with a loop variable. For example:

    int i = 0;
    while (i < 4) {
      System.out.println (count[i]);

This is a standard while loop that counts from 0 up to 4, and when the loop variable i is 4, the condition fails and the loop terminates. Thus, the body of the loop is only executed when i is 0, 1, 2 and 3.

Each time through the loop we use i as an index into the array, printing the ith element. This type of array traversal is very common. Arrays and loops go together like fava beans and a nice Chianti.

Last Update: 2011-01-24