While an array
reference provides a convenient way to refer to an entire collection of
items, it’s important that we be able to access elements in the array
individually. To make this possible,
Java automatically associates each array element with a number that
represents its position in the array.
This number is referred to as the array index (plural form is
indices), and it starts with zero. This means that the first
element in the array always has zero for index, the second element index one,
etc. Since an array has array.length elements in
it (assuming the array reference is array), the index of the last element is array.length – 1.
Remembering this shift by one between the index and position can go a
long way in preventing us from making a common programming error (perhaps the
most common error). To help us
visualize an array, it is often very convenient to draw the array as a
sequence of boxes with the value of each array element placed in the box, and
the corresponding index below the box.
To represent the array numbers above, we would have: numbers
0 1 2 3 4 We can represent the array rivers as: rivers
0 1 2 3 Notice that for both arrays, the index starts at 0,
and it’s the values inside the array that differ. In rivers, each array element stores a String literal, while in numbers, the elements are integer
values. To access an array
element, we use both the array reference and the index of the element in the
array according to the general form: arrayRefernce[index] The following
statement prints out the first element (at index 0) of the array numbers: System.out.println(“The
first array element is “ + numbers[0]); The output value would be 2.
It’s important to distinguish the index into the array (what goes
between the square brackets) and the value stored in the array at that index
(what’s inside the boxes in our diagram above). Given the array rivers declared before, the statement System.out.println(“The “ + rivers[2] + “
is 3964 miles long.”); would output: The
Yangtze is 3964 miles long. Specifying an invalid
index in an array causes a runtime error.
Consider the following
statements: System.out.println(rivers[-1]); System.out.println(rivers[10]); System.out.println(rivers[“ The first statement
causes an error since array indices start with 0, so -1 is invalid. The index in the second statement goes
outside the boundaries of the array rivers (remember that the index of the
last element is one less than the array length, which is 3). The last statement causes an error since
the index value must be a non-negative integer, not a String literal. |