2D Array Creation and Access
Representing a table of related data with a two-dimensional array: arrays of arrays, creating 2D arrays with new and with initializer lists, default values, accessing elements with [row][col], working with whole rows, and finding the number of rows and columns.
A 2D array is stored as an array of arrays, so it is created and indexed much like a 1D array. Its size is established when it is created and cannot be changed, and it can store primitive data or object references. Elements created with new start at the default value for their type; an initializer list of initializer lists creates and fills a 2D array at once. The brackets [row][col] access and modify an element, a single set of brackets gives a whole row, arr.length is the number of rows, and arr[0].length is the number of columns.
1An Array of Arrays
Many kinds of data come in tables: seats in a theater, cells in a spreadsheet, pixels in an image, squares on a game board. A two-dimensional array represents a collection of related data arranged in rows and columns. In Java, a 2D array is stored as an array of arrays: an outer array whose elements are references to rows, where each row is an ordinary 1D array.
Because of this structure, 2D arrays are created and indexed in a way that closely follows 1D arrays. The type int[][] is read as "array of int[]". The size of a 2D array is established at the time of creation and cannot be changed afterward, just like a 1D array, and the elements can be primitive values or object references. The 2D arrays used here are rectangular: every row has the same number of columns.
| 1D array | 2D array | |
|---|---|---|
| Declare and create | int[] a = new int[4]; | int[][] g = new int[3][4]; |
| Initializer list | {1, 2, 3} | { {1, 2, 3}, {4, 5, 6} } |
| Access an element | a[i] | g[row][col] |
| Size | a.length | g.length rows, g[0].length columns |
| Can the size change? | No | No |
2Creating a 2D Array With new
The expression new int[3][4] creates a 2D array with 3 rows and 4 columns. The first number is the number of rows and the second is the number of columns. When a 2D array is created using the keyword new, all of its elements are initialized to the default values for the element data type: 0 for int, 0.0 for double, false for boolean, and null for a reference type.
Creating with new is the right choice when the values will be computed or read later, for example when a program fills a grid from a file or a calculation. The defaults give every element a known starting value, which algorithms such as counting can rely on.
| Element type | Default value after new |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
| Any reference type (String, objects) | null |
Rows, Columns, and Default Values
Predict the output.
int[][] grid = new int[3][4];
System.out.println(grid.length);
System.out.println(grid[0].length);
System.out.println(grid[2][3]);
grid[1][2] = 9;
grid[0][0] = grid[1][2] + 1;
System.out.println(grid[1][2] + " " + grid[0][0]);
3
4
0
9 10
- 1
new int[3][4]creates 3 rows of 4 columns; every element starts at 0. - 2
grid.lengthis the number of rows, 3;grid[0].lengthis the number of columns, 4. - 3
grid[2][3]is the last element and still holds its default, 0. - 4Assignment uses the same
[row][col]brackets: 9 is stored, then 9 + 1 = 10.
new has a fixed number of rows and columns, and its elements start at the default value.Every Element Type Has a Default
Predict the output.
double[][] heights = new double[2][3];
boolean[][] lit = new boolean[2][2];
String[][] labels = new String[2][2];
System.out.println(heights[1][2]);
System.out.println(lit[0][1]);
System.out.println(labels[1][0]);
labels[1][0] = "exit";
System.out.println(labels[1][0].length());
0.0
false
null
4
- 1
doubleelements start at 0.0 andbooleanelements atfalse. - 2Reference elements, such as
String, start atnull: no object yet. - 3After assignment the element refers to "exit", and its
length()is 4.
Using an Element That Is Still null
What happens?
String[][] labels = new String[2][2];
labels[0][0] = "go";
System.out.println(labels[0][0].length());
System.out.println(labels[1][1].length());
- 1
labels[0][0]refers to "go", solength()returns 2. - 2
labels[1][1]was never assigned and holdsnull; calling a method on it throws aNullPointerException.
NullPointerException. Elements of a 2D array of objects must be assigned objects before methods are called on them.A 2D array of String or other objects starts full of null. Calling a method on an element that has not been assigned an object throws a NullPointerException. Assign each element before using it.
3Initializer Lists
The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays; for example, int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };. Each inner list becomes one row, in order, so this array has 2 rows and 3 columns. The size of the array comes from the lists themselves, and no new expression is needed.
Writing each inner list on its own line makes the table shape visible in the code. Every inner list must have the same number of values so that the array is rectangular, and the inner braces are required: a flat list of numbers is a 1D initializer and does not compile as a 2D array.
Creating and Filling at Once
Predict the output.
int[][] seats = { {4, 0, 7}, {2, 9, 5} };
System.out.println(seats.length + " rows, " + seats[0].length + " columns");
System.out.println(seats[0][2]);
System.out.println(seats[1][0]);
2 rows, 3 columns
7
2
- 1Two inner lists make two rows; each has three values, so there are three columns.
- 2
seats[0][2]is row 0, column 2: 7. - 3
seats[1][0]is row 1, column 0: 2.
Missing the Inner Lists
Explain the compile error.
int[][] grid = {1, 2, 3};
- 1Each element of a 2D array is a row, an
int[], so each item in the outer list must itself be a list. - 2The fix wraps the values in inner braces:
int[][] grid = { {1, 2, 3} };creates one row of three columns.
1 is an int, but the outer list needs int[] rows. A 2D initializer list consists of 1D initializer lists.4Accessing Elements by Row and Column
The square brackets [row][col] are used to access and modify an element in a 2D array. When accessing the element at arr[first][second], the first index is used for rows and the second index is used for columns. So grid[1][2] is the element in row 1, column 2, and grid[1][2] = 9; stores 9 there.
Both indices start at 0. The element in the top-left corner is grid[0][0], and moving down increases the row index while moving right increases the column index. Mixing up the order is the most common 2D mistake, so it helps to say "row, then column" every time an element is written.
arr[first][second], the first index is the row and the second index is the column.Computing Positions From Lengths
Predict the output.
String[][] map = { {"tree", "path", "pond"}, {"path", "rock", "path"} };
int lastRow = map.length - 1;
int lastCol = map[0].length - 1;
System.out.println(map[lastRow][lastCol]);
map[0][1] = "bridge";
System.out.println(map[0][1] + " beside " + map[0][2]);
path
bridge beside pond
- 1Last row is
map.length - 1= 1; last column ismap[0].length - 1= 2. - 2
map[1][2]is "path". - 3Modifying
map[0][1]replaces "path" with "bridge" in row 0.
[arr.length - 1][arr[0].length - 1].In grid[r][c] the row always comes first. Writing grid[c][r] reads the wrong element, or throws an exception when there are more columns than rows. When translating from a picture, find the row first.
5Working With a Whole Row
A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index. seats[1] is row 1, an int[]; it has its own length and can be passed to any method that takes a 1D array.
The row expression gives a reference to the row stored in the 2D array, not a copy. Storing it in a variable such as int[] back = seats[1]; creates an alias: changing back[0] changes seats[1][0]. This is useful when a method should process one row, and surprising when a separate copy was intended.
A Row Is a 1D Array
Predict the output.
int[][] seats = { {4, 0, 7}, {2, 9, 5} };
int[] back = seats[1];
System.out.println(back.length);
System.out.println(back[2]);
back[0] = 8;
System.out.println(seats[1][0]);
3
5
8
- 1
seats[1], with one set of brackets, is row 1: anint[]of length 3. - 2
back[2]is the same element asseats[1][2]: 5. - 3Not a copy.
backrefers to the same row object, soback[0] = 8changesseats[1][0].
After int[] back = seats[1];, both names refer to the same row. Any change made through back appears in seats. To keep the original unchanged, copy the values into a new array element by element.
6Sizes and Valid Indices
The number of rows contained in a 2D array can be accessed through the length attribute. The valid row index values are 0 through one less than the number of rows, inclusive. The number of columns can be accessed through the length attribute of one of the rows, and the valid column index values are 0 through one less than the number of columns, inclusive. For a 2D array named values, the number of rows is values.length and the number of columns is values[0].length.
Using an index value outside of these ranges results in an ArrayIndexOutOfBoundsException. Computing positions from the lengths, such as values.length - 1 for the last row, keeps code correct when the size of the table changes.
arr.length; the number of columns is the length of one row, arr[0].length.| Expression | Meaning | For grid = new int[3][4] |
|---|---|---|
grid.length | Number of rows | 3 |
grid[0].length | Number of columns (length of a row) | 4 |
grid[r] | Row r, an int[] | Valid for r = 0 to 2 |
grid[r][c] | Element in row r, column c | Valid for c = 0 to 3 |
grid[grid.length - 1][grid[0].length - 1] | Last element | grid[2][3] |
One Row Too Far
What happens?
int[][] seats = { {4, 0, 7}, {2, 9, 5} };
System.out.println(seats[1][2]);
System.out.println(seats[2][1]);
- 1
seats[1][2]is valid: row 1 is the last row and column 2 the last column. It prints 5. - 2
seats[2][1]asks for row 2, but valid rows are 0 and 1, so Java throws anArrayIndexOutOfBoundsException.
ArrayIndexOutOfBoundsException. Row indices must be less than arr.length, and column indices less than arr[0].length.arr.length counts rows, not columns. For a table with 3 rows and 4 columns, arr.length is 3. The number of columns is arr[0].length, the length of a row.
Four Habits for 2D Arrays
1. Row, Then Column
arr[row][col], every time.
2. Two Lengths
arr.length rows; arr[0].length columns.
3. Rows Are Arrays
arr[r] is a 1D array, shared, not copied.
4. Know the Defaults
0, 0.0, false, or null after new.
A 2D array is stored as an array of arrays, so the way 2D arrays are created and indexed is similar to 1D array objects. The size of a 2D array is established at the time of creation and cannot be changed, and 2D arrays can store either primitive data or object reference data. When a 2D array is created using the keyword new, its elements are initialized to the default values for their type: 0, 0.0, false, or null. The initializer list for a 2D array consists of initializer lists that represent 1D arrays. The square brackets [row][col] are used to access and modify an element, with the first index for rows and the second for columns. A single row is accessed with one set of brackets containing the row index. The number of rows is arr.length and the number of columns is arr[0].length; an index outside these ranges results in an ArrayIndexOutOfBoundsException.