4.11 - 2D Array Creation and Access
A 2D array is basically an array of arrays. Its size is locked in at creation, just like a regular array, and it can hold either primitives or object references.
On the AP exam, 2D arrays are always rectangular: every row has the same number of columns. 2D arrays whose rows have different lengths are outside the scope of the course.
int[][] grid = new int[3][4]; // 3 rows, 4 columns
In
new int[3][4], the first number is how many rows there are and the second is how many columns. Every row is its own 1D array of length 4.Just like a 1D array, every element starts at the default value for its type when you create it with
new.double[][] prices = new double[2][2]; // every element is 0.0 boolean[][] taken = new boolean[3][5]; // every element is false String[][] seats = new String[2][3]; // every element is null
You can also use a nested initializer list:
int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };
Each inner list is one row, so arr2D has 2 rows and 3 columns:
col 0 | col 1 | col 2 | |
row 0 | 1 | 2 | 3 |
row 1 | 4 | 5 | 6 |
Square brackets with
[row][col] let you access or modify a specific element. The first index is the row, the second is the column.System.out.println(arr2D[1][2]); // 6, second row, third column arr2D[0][0] = 100; // changes the top-left element
You can grab an entire row (as its own 1D array) using just one set of brackets:
int[] firstRow = arr2D[0]; // {1, 2, 3}
firstRow refers to the actual row inside arr2D, not a copy. So firstRow[0] = 50; would change arr2D[0][0] to 50 as well.To find dimensions:
int numRows = arr2D.length; // number of rows int numCols = arr2D[0].length; // number of columns (based on row 0)
Same rule as before, going out of range throws an
ArrayIndexOutOfBoundsException.Valid row indices run from 0 to
arr2D.length - 1, and valid column indices run from 0 to arr2D[0].length - 1. For arr2D above, that’s rows 0 to 1 and columns 0 to 2:System.out.println(arr2D[1][2]); // 6, the bottom-right element System.out.println(arr2D[2][0]); // ArrayIndexOutOfBoundsException, there's no row 2 System.out.println(arr2D[0][3]); // ArrayIndexOutOfBoundsException, there's no column 3