2D Arrays: Grids and Tables

An array of arrays

A 2D array is a grid with rows and columns, like a cinema seating plan or a spreadsheet.

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6}
        };
        System.out.println(grid[0][2]);
        System.out.println(grid[1][0]);
        System.out.println("Rows: " + grid.length);
        System.out.println("Columns: " + grid[0].length);
    }
}

Output

3
4
Rows: 2
Columns: 3

grid[row][column]: first the row, then the column. Both start at 0.

Looping through a grid

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] + " ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3 
4 5 6 
7 8 9 

Making an empty grid

public class Main {
    public static void main(String[] args) {
        int[][] table = new int[3][4];
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 4; c++) {
                table[r][c] = (r + 1) * (c + 1);
            }
        }
        for (int[] row : table) {
            for (int value : row) {
                System.out.print(value + "\t");
            }
            System.out.println();
        }
    }
}

Output

1	2	3	4	
2	4	6	8	
3	6	9	12	

Tip: new int[3][4] means 3 rows and 4 columns. Each row is itself an int[], which is why the for-each loop uses int[] row.

HOME LABS COMMUNITY DASHBOARD