Bounds Checking

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

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

Bounds Checking

When your program is running and it tries to acess 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?