int[] data = new int[10];

A good answer might be:

  1. What is the length of the array data? 10
  2. What are the indexes of data? 0..9

Bounds Checking

Recall that:

The length of an array is how many slots it has. An array of length N has slots indexed 0..(N-1)

Indexes must be an integer type. It is OK to have spaces around the index of an array, for example data[1] and data[ 1 ] are exactly the same as far as the compiler is concerned.

Say that an array were declared:

int[] data = new int[10];

It is not legal to refer to a slot that does not exist:

data[ -1 ] always illegal
data[ 10 ] illegal   (given the above declaration)
data[ 1.5 ] always illegal
data[ 0 ] always OK
data[ 9 ] OK   (given the above declaration)

If you have one of the above always illegal expressions in your program, your program will not compile. Often the size of an array is not known to the compiler (since the array is constructed as the program is running, its length does not need to be known to the compiler.) However, if your running program tries to refer to a slot that does not exist, an exception will be thrown, and (unless another part of your program does something about it) your program be terminated.

Bounds checking

QUESTION 6:

Here is a declaration of another array:

int[] scores = new double[25];

Which of the following are legal?

scores[ 0 ]
scores[1]
scores[ -1 ]
scores[ 10]
scores[ 25 ]
scores[ 24 ]