Two Dimensional Arrays

5. Bounds Checking


Answer:

No. The indicated array element (cell) does not exist.

Bounds Checking

When your program is running and it tries to access an element of an array, the Java virtual machine checks that the array element actually exists. This is called bounds checking. If your program tries to access an array element that does not exist, the Java virtual machine will generate an:

ArrayIndexOutOfBoundsException

Ordinarily, this will halt your program. Of course, as with 1D arrays, array indexes must be an integer type.

It makes no sense to access gradeTable[ 3.5 ][ 2 ].

As with a 1D array, an array index may be an integer literal, a variable of integer type, a method that evaluates to an integer, or an arithmetic expression involving all of these things:

  • gradeTable[ 3 ][ j ] = 34;
  • sum = gradeTable[ i ][ j ] + gradeTable[ i ][ j+1 ] ;
  • value = gradeTable[ 2 ][ someFunction() ] ;
  • gradeTable[ 1 ][ 0 ] = gradeTable[ i+3 ][ someFunction()-2 ] ;

We are not likely to need a statement as complicated as the last one.


Question 5:

(Review: ) must the elements of a 2D array be all of the same type?