10.3 One-Dimensional Arrays | 491
do not check for this kind of error, but Java does. If your code attempts to use an
out-of-bounds array index, an ArrayIndexOutOfBoundsExceptionis thrown. Rather than
try to catch this error, you should write your code so as to prevent it.
In Java, each array that is instantiated has a publicinstance variable, called
length, associated with it that contains the number of components in the array.
We can use lengthwhen processing the components in the array to keep from hav-
ing an out-of-bounds error. How? Array-processing algorithms often use forloops
to step through the array elements one at a time. The following loop zeroes out
the 100-element alphaarray:
for (int index = 0; index < alpha.length; index++)
alpha[index] = 0.0;
Use this pattern—initialize the counter to zero, and then use a “less than” test against the
size of the array as recorded in length—and you can be sure that your counter is within the
bounds of the array. If your code crashes with an ArrayIndexOutOfBoundsException, immediately
verify that your relational operator is the less than operator, not the less than or equal to op-
erator.
Aggregate Array Operations
We can assign one array to another and we can compare two arrays for equality—but we
might not get the answer we expect. Arrays, like classes, are reference types. As a conse-
quence, the value stored in a reference variable is not the object itself but rather the address
of where the object is stored. Let’s see what happens when we test two arrays for equality
and assign one array to another.
int[] numbers = {2, 4, 6};
int[] values = new int[3];
values[0] = 2;
values[1] = 4;
values[2] = 6;
if (numbers == values)
...
numbers = values;
if (numbers == values)
...
The first ifexpression is false, because the variables numbersand valueshold two different
memory addresses. (See Figure 10.6a.) The next statement takes the contents of values(the
address where the array is stored) and stores it into numbers. The next ifexpression is true,
because the two variables now hold the same memory address. (See Figure 10.6b.)
You should not be surprised at this example. An assignment for reference types is a
shallow assignment; an equality test for reference types is a shallow test. If you want to
have a deep test, you must write a method to do the comparison, element by element.
Out-of-bounds array index
An index value that is either less
than 0 or greater than the array
size minus 1