When working with two dimensional arrays, it is beneficial to think of them as arrays holding arrays. For example, a statement declaring a 2D array with an initializer list would look like:
int[ ][ ] int2D = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 0, 1, 2}};
However, consider the following representation of this array:
Row #1 contains the array {1, 2, 3, 4}
Row #2 contains the array {5, 6, 7, 8}
Row #3 contains the array {9, 0, 1, 2}
The size of this array is 3 rows and 4 columns. In a mathematics class, we would call this a 3 by 4 matrix. In addition, we should be able to identify the indices for each element of the array as an ordered pair. For example, the number 3 has location 0, 2. This means that int2D[0][2] = 3. The array below shows the index location for each element of the array int2D.
Practice
Evaluate the following:
[1] int2D[1][3] = [2] int2D[3][0] =
Answers:
[1] int2D[1][13] = 8
[2] int2D[3][0] = undefined, causes an ArrayIndexOutOfBoundsException error
An ArrayIndexOutOfBoundsException error occurs when you try to access a location that does not exist in a given array.
2D Array Lengths
When considering 2D arrays as arrays holding arrays it makes it easier to evaluate the length field.
int2D.length = ???
Remember int2D is an array holding arrays, so what is the length of int2D? Once you’ve found the length of int2D, next evaluate:
int2D[0].length = ???
All of the properties, techniques, and characteristics of one-dimensional arrays can be extended to two-dimensional arrays with some modifications in coding. For example, the for loop will need to vary for two-dimensional arrays depending on which part of the array the code is iterating. Consider the following statements and when to use each.
for(int i = 0; i < int2D.length ; i++)
vs.
for(int i = 0; i < int2D[0].length ; i++)
Recall, it is beneficial to think of two-dimensional arrays as "arrays" holding "arrays". With this in mind then int2D.length counts the number of arrays being stored, and int2D[0] counts how many values are stored by the first array, i.e. the array stored at the zero index of int2D.