Memra

Multidimensional & jagged arrays

Arrays of arrays — rectangular grids and ragged rows.

Arrays of arrays

Java has no true 2D array type — it has arrays whose elements are themselves arrays. A rectangular 3×4 grid:

int[][] grid = new int[3][4];  // 3 rows, each holding 4 ints
grid[0][0] = 1;
grid[2][3] = 99;

An initialiser syntax:

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};

Because each row is an independent array, rows can have different lengths — a jagged (ragged) array:

int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[5];
jagged[2] = new int[1];

Nested iteration uses each row's own length:

for (int r = 0; r < matrix.length; r++) {
    for (int c = 0; c < matrix[r].length; c++) {
        System.out.print(matrix[r][c] + " ");
    }
    System.out.println();
}
NORMAL ~/memra/learn/java-from-zero/multidimensional-arrays utf-8 LF