Two Dimensional Arrays
This chapter expands our discussion on one-dimensional arrays to two dimensional arrays. A two dimensional array is a data structure that contains a collection of cells laid out in a two dimensional grid, similar to a table with rows and columns although the values are still stored linearly in memory. Each cell in a two dimensional array can be accessed through two indexes that specify the row number and column number respectively. Like s one dimensional array, the range of each index is from zero to the size of the row or column minus one. A nested for loop is commonly used to initialize, manipulate, and access the values in a two dimensional array.
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?