Full explanation, figures and traced examples: Topic 4.11 study guide.
Recap
A 2D array is an array of arrays: the outer array holds one reference per row and each reference leads to a 1D row array. For the exam arr[row][col]: first index row, second index column. Only rectangular arrays are in scope. The size is fixed when the array is created.
int[][] grid = new int[3][4]; // 3 rows, 4 columns, all 0
int[][] m = { {1, 2, 3}, {4, 5, 6} }; // 2 rows, 3 columns
int rows = m.length; // 2
int cols = m[0].length; // 3
int x = m[1][2]; // 6
m[0][1] = 20; // change one element
int[] row1 = m[1]; // alias of the second row
Key relationships
| Item | Rule |
|---|---|
| Number of rows | arr.length |
| Number of columns | arr[0].length (or arr[r].length) |
| Total elements | arr.length * arr[0].length |
| Valid row index | 0 to arr.length - 1 |
| Valid column index | 0 to arr[0].length - 1 |
Defaults after new |
0, 0.0, false, null by element type |
| Row | arr[r] is a 1D array and a reference (alias, not copy) |
| Bad index | ArrayIndexOutOfBoundsException |
null element |
calling a method on it throws NullPointerException |
Assumptions
- The array is rectangular (all rows the same length).
- The array variable is not
null. - Indices are checked against the correct dimension: rows against
arr.length, columns againstarr[0].length.
A mini-example to rehearse
int[][] grid = new int[3][4]; grid[1][2] = 7; grid[2][0] = grid[1][2] + 1; leaves row 1 as 0 0 7 0 and row 2 as 8 0 0 0; grid.length is 3 and grid[0].length is 4. With int[][] m = { {1, 2, 3}, {4, 5, 6} }, m[1][2] + m[0][1] is 6 + 2 = 8. int[] row = m[1]; row[0] = 40; changes m[1][0] to 40, because the row is shared. m[2][0] and m[0][3] both throw ArrayIndexOutOfBoundsException.
Mistakes to avoid
- Reversing row and column.
- Using
arr.lengthfor the number of columns. - Expecting
""in a newString[][](it isnull). - Treating
arr[r]as a copy of the row. - Using
<=withlengthin an index check. - Forgetting that the size cannot change after creation.
How this topic is usually tested
- Give the value of an element, the number of rows or columns, or the total size.
- Trace assignments and write the final table.
- Spot the out-of-range index or the null element that causes an exception.
- Write short statements or methods that read or fill a cell or a row.
Quick self-check
new int[3][4]: how many rows and columns? 3 rows and 4 columns, 12 elements, all 0.- For
{ {1, 2, 3}, {4, 5, 6} }, what ism[0][2]? 3 - What is
m[1].length? 3 - A new
String[2][2]holds what in each cell?null - Which of
m[2][0]andm[1][2]throws for the 2-by-3 arraym?m[2][0](row 2 does not exist).