Arrays
This chapter introduces arrays, a common multi-dimensional data structure used to store data of the same type. (Note that a class is a "data type" in this sense.) Arrays have some number of dimensions and a number of elements in each dimension. These are established when the array is created. The range of the array's index in each dimension goes from zero to the number of that dimension's elements minus one. A for loop is commonly used to initialize, manipulate, and access the values in an array. Here, we treat one-dimensional arrays, sometimes called vectors.
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?