go to previous page   go to home page   go to next page hear noise

Answer:

int[] data = new int[10];
  1. What is the length of the array data? 10
  2. What are the indexes of data? 0, 1, 2, ..., 8, 9

Bounds Checking

int[] data = new int[10];
data[ -1 ] always illegal
data[ 10 ]    illegal
(given the above declaration)   
data[ 1.5 ] always illegal
data[ 0 ] always OK if the array exists
data[ 9 ] OK
(given the above declaration)
data[ j ] can't tell without more information
(depends on the current value of j)

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?

scores[ 0 ] scores[1] scores[ -1 ]
scores[ 10] scores[ 25 ] scores[ 24 ]
scores[ 1.2] scores [2] scores [ 4 ]

go to previous page   go to home page   go to next page