Skip to content
Laviyx Learn

Try

Java course menu

Java 2D Arrays: Grids, Matrices and Jagged Arrays

Work with tables and grids in Java: creating 2D arrays, rows and columns, nested loops, printing with Arrays.deepToString, row and column totals, transposing a matrix, and jagged arrays whose rows have different lengths.

Beginner11 min readUpdated
On this page

Many problems involve grids: a seating plan, a game board, a timetable, a spreadsheet or a matrix. In Java, a 2D array is an array of arrays: each element of the outer array is one row.

Creating a 2D array#

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
        };

        System.out.println(grid[0][0] + " " + grid[1][2] + " " + grid[2][3]);
        System.out.println(grid.length + " rows, " + grid[0].length + " columns");

        int[][] empty = new int[2][3];   // 2 rows of 3 zeros
        System.out.println(Arrays.deepToString(empty));
    }
}
Output
1 7 12
3 rows, 4 columns
[[0, 0, 0], [0, 0, 0]]
  • grid[row][col] reaches one cell; both indexes start at 0.
  • grid.length is the number of rows; grid[r].length is the length of row r.
  • Arrays.deepToString prints nested arrays (Arrays.toString would print the rows' references).

Looping over a grid#

The outer loop walks the rows; the inner loop walks the columns of the current row:

Java
public class Main {
    public static void main(String[] args) {
        int[][] grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                System.out.print(grid[r][c] + "\t");
            }
            System.out.println();
        }

        int sum = 0;
        for (int[] row : grid) {
            for (int value : row) {
                sum += value;
            }
        }
        System.out.println("Sum: " + sum);
    }
}
Output
1	2	3	
4	5	6	
7	8	9	
Sum: 45

Row and column totals#

Java
public class Main {
    public static void main(String[] args) {
        int[][] sales = {
            {120, 150, 110},
            {90, 95, 130},
            {200, 180, 210},
        };

        for (int r = 0; r < sales.length; r++) {
            int rowTotal = 0;
            for (int v : sales[r]) rowTotal += v;
            System.out.println("Shop " + (r + 1) + ": " + rowTotal);
        }

        for (int c = 0; c < sales[0].length; c++) {
            int colTotal = 0;
            for (int r = 0; r < sales.length; r++) colTotal += sales[r][c];
            System.out.println("Month " + (c + 1) + ": " + colTotal);
        }
    }
}
Output
Shop 1: 380
Shop 2: 315
Shop 3: 590
Month 1: 410
Month 2: 425
Month 3: 450

For column totals, the column loop goes on the outside.

A game board#

Java
public class Main {
    public static void main(String[] args) {
        char[][] board = {
            {'X', 'O', 'X'},
            {' ', 'X', 'O'},
            {'O', ' ', 'X'},
        };

        for (char[] row : board) {
            StringBuilder line = new StringBuilder();
            for (char cell : row) line.append('[').append(cell).append(']');
            System.out.println(line);
        }

        boolean diagonal = board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X';
        System.out.println("X wins on the diagonal: " + diagonal);
    }
}
Output
[X][O][X]
[ ][X][O]
[O][ ][X]
X wins on the diagonal: true

Transposing a matrix#

Transposing swaps rows and columns: [r][c] moves to [c][r]:

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] m = {{1, 2, 3}, {4, 5, 6}};
        int[][] t = new int[m[0].length][m.length];

        for (int r = 0; r < m.length; r++) {
            for (int c = 0; c < m[0].length; c++) {
                t[c][r] = m[r][c];
            }
        }
        System.out.println(Arrays.deepToString(t));
    }
}
Output
[[1, 4], [2, 5], [3, 6]]

Jagged arrays#

Because each row is a separate array, rows can have different lengths. Pascal's triangle is a classic example:

Java
public class Main {
    public static void main(String[] args) {
        int rows = 5;
        int[][] pascal = new int[rows][];

        for (int r = 0; r < rows; r++) {
            pascal[r] = new int[r + 1];
            pascal[r][0] = 1;
            pascal[r][r] = 1;
            for (int c = 1; c < r; c++) {
                pascal[r][c] = pascal[r - 1][c - 1] + pascal[r - 1][c];
            }
        }

        for (int[] row : pascal) {
            StringBuilder line = new StringBuilder();
            for (int v : row) line.append(v).append(' ');
            System.out.println(line.toString().trim());
        }
    }
}
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

new int[rows][] creates the outer array with empty (null) rows; each row is then created with its own length. Always use grid[r].length for the inner loop when rows may differ.

Common mistakes#

Practice#

Practice exercise

Check whether {{2, 7, 6}, {9, 5, 1}, {4, 3, 8}} is a magic square: every row, column and both diagonals have the same sum.

Show solution
Java
public class MagicSquare {
    public static void main(String[] args) {
        int[][] m = {{2, 7, 6}, {9, 5, 1}, {4, 3, 8}};
        int n = m.length;

        int target = 0;
        for (int v : m[0]) target += v;

        boolean magic = true;
        int diag1 = 0;
        int diag2 = 0;
        for (int i = 0; i < n; i++) {
            int row = 0;
            int col = 0;
            for (int j = 0; j < n; j++) {
                row += m[i][j];
                col += m[j][i];
            }
            if (row != target || col != target) magic = false;
            diag1 += m[i][i];
            diag2 += m[i][n - 1 - i];
        }
        if (diag1 != target || diag2 != target) magic = false;

        System.out.println("Magic square: " + magic + " (sum " + target + ")");
    }
}
Output
Magic square: true (sum 15)

Key takeaway#

Finished this lesson?