Arrays
6. Bounds Checking
Answer:
int[] data = new int[10];
- What is the length of the array
data
? 10 - What are the indexes of
data
? 0, 1, 2, ..., 8, 9
Bounds Checking
Recall that:
The length of an array is how many cells it has. An array of length N has cells indexed 0..(N-1)
Indexes must be an integer type. It is OK to have spaces around the index of a subscripted variable, for example data[1]
and data[ 1 ]
are exactly the same as far as the compiler is concerned.
It is not legal to refer to a cell that does not exist.
Say that an array were declared:
int[] data = new int[10];
The table shows some subscripted variables of this array.
If your program contains an expression that is always illegal, it will not compile. But often the size of an array is not known to the compiler. The size of an array often is determined by data at run time. Since the array is constructed as the program is running, the compiler does not know its length and can't detect some errors.
As a Java program is running, each time an array index is used it is checked to be sure that it is OK. This is called bounds checking, and is extremely important for catching errors. If an executing program refers to a cell that does
not exist, an ArrayIndexOutOfBoundsException
is thrown, and (usually) the program is terminated. (See a future chapter for more on exceptions.)
Question 6:
Here is a declaration of another array:
double[] scores = new double[25];
Which of the following are legal?