Java Reference
In-Depth Information
TIP: Use for Loops with Arrays
The second for loop in Display 6.2 illustrates a common way to step through an
entire array using a for loop:
for (index = 0; index < score.length; index++)
System.out.println(score[index] + " differs from max by "
+ (max score[index]));
The for loop is ideally suited for performing array manipulations.
PITFALL: Array Indices Always Start with Zero
The indices of an array always start with 0 and end with the integer that is one less than
the size of the array.
PITFALL: Array Index Out of Bounds
The most common programming error made when using arrays is attempting to use a
nonexistent array index. For example, consider the following:
int[] a = new int [6];
When using the array a , every index expression must evaluate to one of the integers 0
through 5 . For example, if your program contains the indexed variable a[i] , the i
must evaluate to one of the six integers 0 , 1 , 2 , 3 , 4 , or 5 . If i evaluates to anything
else, that is an error. When an index expression evaluates to some value other than
those allowed by the array declaration, the index is said to be out of bounds . If your
program attempts to use an array index that is out of bounds, then your program will
end with an error message. 2 Note that this is a run-time error message, not a compiler
error message.
Array indices get out of bounds most commonly at the first or last iteration of a loop
that processes the array. So, it pays to carefully check all array processing loops to be cer-
tain that they begin and end with legal array indices.
illegal
array index
2 Technically speaking, an ArrayIndexOutOfBoundsException is thrown. We will discuss exceptions
in Chapter 9. Until you learn about handling exceptions, exceptions will simply appear as error con-
ditions to you.
Search WWH ::




Custom Search