Row-major rectangular 2D arrays
A 2D array in Java is an array of arrays. The most common form is rectangular (every row has the same length) and accessed in row-major order (the first index selects the row; the second selects the column within that row).
int[][] grid = new int[3][4]; // 3 rows, 4 columns; all 12 slots initialised to 0
grid[0][0] = 1; // row 0, column 0
grid[2][3] = 99; // row 2, column 3 (the bottom-right corner)
System.out.println(grid.length); // 3 (number of rows)
System.out.println(grid[0].length); // 4 (length of row 0)
Three facts the language enforces:
1. grid.length is the number of rows. grid is an array of length 3; each element of that array is itself an int[] of length 4. 2. grid[i].length is the length of row i. For a rectangular array, this is the same for every i. The "number of columns" is grid[0].length by convention (any row works, but row 0 is the canonical one). 3. There is no grid.length[1] or grid.cols. Java does not store the dimensions as a separate property. The "number of columns" must be read from a row.
Constructing a rectangular grid
new int[rows][cols] allocates everything at once: the outer array of length rows, plus rows inner arrays each of length cols. All rows * cols int slots are initialized to 0. The same form works for any element type: String[][] board = new String[8][8]; allocates a chessboard's worth of null references.
Literal-initializer form:
final int[][] grid = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Each inner {...} is a row. The number of inner literals is the row count; the length of each inner literal is the column count for that row. If the inner lengths differ, the result is a jagged array.
Row-major access
The convention grid[row][col] (row first, column second) is universal in Java code and matches mathematical notation (A[i][j] for matrices). Visualizing:
col 0 col 1 col 2 col 3
row 0: [ 1 , 2 , 3 , 4 ]
row 1: [ 5 , 6 , 7 , 8 ]
row 2: [ 9 , 10 , 11 , 12 ]
grid[1][2] is the value 7 (row 1, column 2). The memory layout is "first row stored consecutively, then second row, then third," but this layout detail rarely matters at the CSCD 210 level. The pedagogical commitment is "row first" in the indexing syntax.
In other languages
- C / C++:
int grid[3][4];allocates as a single block of 12 ints, row-major. Same indexing syntax. - Python:
numpy.array(...)andnumpy.zeros((3, 4))are the analog; tuples for shape, indexedgrid[i, j](single bracket pair with comma) orgrid[i][j]. - MATLAB: column-major by default;
A(i, j)is rowi, columnj. Beware when porting code. - JavaScript: no fixed-shape 2D arrays;
[[1,2],[3,4]]is an array of arrays, identical to Java's structure.