Java Reference ยท Types and Literals
Multidimensional arrays
Reference for Java multidimensional arrays: 2D grids, jagged arrays, creating and filling nested arrays, deep copying and printing with Arrays.deepToString.
Java does not have true multidimensional arrays. A two-dimensional array is an array whose elements are themselves arrays. int[][] grid is an array of int[] rows. Because each row is a separate object, rows can have different lengths (a "jagged" array) and can even be null.
Rows are allocated as part of new int[rows][cols]. You can also leave the inner dimension out, new int[3][], and create each row yourself.
int[][] grid = new int[3][4]; // 3 rows, 4 columns int[][] tri = {{1}, {1, 1}, {1, 2, 1}};
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Type[][] name = new Type[rows][cols]; Type[][] name = new Type[rows][]; // rows created later Type[][] name = {{...}, {...}}; Type[][][] cube = new Type[a][b][c];
| Expression | Meaning |
|---|---|
grid.length |
Number of rows. |
grid[r].length |
Length of row r; may differ between rows. |
grid[r][c] |
One element. |
Arrays.deepToString(grid) |
Readable text for nested arrays. |
Arrays.deepEquals(a, b) |
Element-wise comparison of nested arrays. |
Usage notes
- Rectangular or jagged. Use
grid[r].lengthin the inner loop rather than a fixed column count when rows may vary. clone()is shallow. Copying a 2D array copies only the row references, so both arrays share the rows. Clone each row (or use streams:Arrays.stream(a).map(int[]::clone).toArray(int[][]::new)).- Printing.
Arrays.toString(grid)prints row identities; usedeepToString(). Arrays.equals()andArrays.sort()on a 2D array treat rows as objects; usedeepEquals(), or sort with a comparator on the rows.- Memory and speed. Each row is an object with a header. Iterate row by row (row-major) for good cache behavior. For very large matrices, a flat 1D array indexed by
r * cols + cis more compact. - Memory is allocated up front:
new int[10000][10000]needs about 400 MB and will probably fail withOutOfMemoryError. - Java has no
array[r, c]syntax. Dimensions are always written as separate brackets.