6.2 Multidimensional & Jagged (Ragged) Arrays
Key Takeaways
A Java multidimensional array has array references as its elements. The referenced rows can have different lengths or be null.
Brackets in multidimensional declarations may appear on the type, on the variable, or split across both (
int[][] g,int[] g[],int g[][]), and inint[] a, b[];ais 1D whilebis 2D.When instantiating with
new, dimensions must be specified left to right without gaps:new int[3][]is legal, whereasnew int[][3]andnew int[2][][4]fail compilation.Indexing an unallocated row (
grid[1][0]whengrid[1]isnull) throwsNullPointerException, whereas indexing an empty row (new int[0]) throwsArrayIndexOutOfBoundsException.Nested brace initializers can appear in declarations or array creation expressions. In a later row assignment, use
grid[0] = new int[]{1, 2};.
Multidimensional & Jagged (Ragged) Arrays
A Java 2D array is an outer array whose elements hold references to row arrays. A rectangular allocation gives the rows equal lengths, while the type also permits unequal lengths and null rows. Extending this model, a 3D array is a 1D array of references to 2D arrays. Because each inner array is an independent heap object, rows in a 2D array can have completely different lengths — or even be null.
Legal & Mixed Multidimensional Declarations
The total number of square-bracket pairs associated with a variable determines its dimensionality. Those brackets may appear before the identifier, after the identifier, or split between the two:
int[][] m1; // Preferred: 2D array of int
int[] m2[]; // Legal: 1 bracket on type + 1 on variable = 2D
int m3[][]; // Legal: both brackets on variable = 2D
When multiple variables share one declaration statement, brackets on the type apply to all variables, while brackets after an identifier add extra dimensions only to that variable:
int[] a, b[]; // a is 1D (int[]), b is 2D (int[][])
int[][] x, y[]; // x is 2D (int[][]), y is 3D (int[][][])
int p[], q[][]; // p is 1D (int[]), q is 2D (int[][])
As with 1D arrays, placing sizes inside the declaration (int[2][3] grid;) fails to compile.
Rectangular vs. Partial (Jagged) Instantiation
When you instantiate a multidimensional array with new, Without an initializer list, specify the outer dimension first. After you leave one dimension empty, all remaining dimensions must be empty. With an initializer list, leave all dimensions empty and let the initializer set the lengths.
// Rectangular allocation: outer length 2, each row allocated with length 3
int[][] rect = new int[2][3];
// Partial (jagged) allocation: outer length 3, inner rows start as null
int[][] jagged = new int[3][];
// 3D partial allocations
int[][][] cube1 = new int[2][3][]; // Legal: 2x3 grid of null int[] refs
int[][][] cube2 = new int[2][][]; // Legal: outer length 2 of null int[][] refs
// Illegal gap in dimensions:
// int[][] bad1 = new int[][3]; // COMPILE ERROR: missing outer size
// int[][][] bad2 = new int[2][][4]; // COMPILE ERROR: gap at middle dimension
| Expression | Legal? | Heap Objects Created Initially |
|---|---|---|
new int[2][3] | Yes | 1 outer int[2][] + 2 inner int[3] arrays (all 0) |
new int[3][] | Yes | 1 outer int[3][] filled with three null references |
new int[2][3][] | Yes | 1 int[2][][], 2 int[3][] filled with null |
new int[][3] | Compile Error | Leftmost dimension is required |
new int[2][][4] | Compile Error | Cannot specify a right dimension after an empty one |
Allocating and Replacing Jagged Rows
Because each slot of an int[][] is an ordinary int[] reference, you can assign rows of unequal lengths or replace a row in an existing array. The existing row object keeps its original length:
int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2}; // Row 0 has length 2
jagged[1] = new int[4]; // Row 1 has length 4 (all zeros)
jagged[2] = new int[]{9}; // Row 2 has length 1
// Even a "rectangular" array can become jagged later:
int[][] rect = new int[2][3];
rect[0] = new int[5]; // Legal! Replaces row 0 with a length-5 array
Warning
Bare braces can initialize a declared array or appear inside a larger array initializer. Writing jagged[0] = {1, 2}; fails compilation; you must write jagged[0] = new int[]{1, 2}; when assigning an individual row.
grid.length vs. grid[i].length and the NullPointerException Trap
In a 2D array grid, grid.length returns the number of row references in the outer array, while grid[i].length returns the number of elements in row i. Notice the dramatic difference between an unallocated row (null) and an empty row (new int[0]):
int[][] grid = new int[3][];
grid[0] = new int[]{1, 2};
// grid[1] remains null
grid[2] = new int[0];
System.out.println(grid.length); // 3
System.out.println(grid[0].length); // 2
System.out.println(grid[2].length); // 0
// System.out.println(grid[1].length); // Runtime: NullPointerException!
// System.out.println(grid[1][0]); // Runtime: NullPointerException!
// System.out.println(grid[2][0]); // Runtime: ArrayIndexOutOfBoundsException!
Notice that grid[1][0] throws NullPointerException (not ArrayIndexOutOfBoundsException) because Java evaluates grid[1] first, gets null, and attempts to index null at 0. By contrast, grid[2] is a valid non-null array object of length 0, so grid[2][0] throws ArrayIndexOutOfBoundsException.
2D Literal Initializers & Safe Traversal
Just like 1D arrays, multidimensional arrays support nested brace initializers in declarations as well as anonymous nested arrays:
// Declaration-only nested initializer (creates a jagged 3-row array)
int[][] matrix = {
{1, 2},
{3},
{4, 5, 6}
};
// Anonymous 2D array for reassignment or method calls
matrix = new int[][]{{10, 20}, {30}};
When traversing a jagged array with nested for loops, always bound the inner loop by grid[i].length (not grid[0].length or grid.length) and guard against null rows when rows might be unallocated:
for (int i = 0; i < grid.length; i++) {
if (grid[i] == null) {
continue;
}
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
You can also iterate with nested enhanced for loops (for (int[] row : matrix) { for (int val : row) { ... } }), remembering that row will be null on any unallocated row unless checked before the inner loop.
Which declaration and instantiation statement fails to compile in Java SE 8?
int[] a, b[]; a = new int[2]; b = new int[2][];
int[][] grid = new int[][3];
int[] grid[] = new int[3][];
int[][] grid = {{1, 2}, {3}};
What happens when the following code runs?
int[][] table = new int[3][];
table[0] = new int[]{5, 10};
table[2] = new int[0];
System.out.println(table[1][0]);
Prints 0
Fails to compile because table[1] was never initialized
Throws ArrayIndexOutOfBoundsException
Throws NullPointerException
What does the following code print?
int[][] m = {{1, 2}, {3}, {4, 5, 6}};
m[1] = new int[4];
System.out.println(m.length + ":" + m[1].length + ":" + m[1][2]);
3:4:0
3:1:0
4:4:0
Throws ArrayIndexOutOfBoundsException
Sections you finish are checked off in the contents.