AI Hints
Home›Java Tutorial›Two-Dimensional Arrays, Common Array Mistakes, Practice: Top Scores
Java · Lesson 52 of 120

Two-Dimensional Arrays

Rows and columns.

⏱ 2 min read▶ Video at 1:04:59🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Some data comes in a grid. Seats in a cinema, cells in a spreadsheet, squares on a board. A two dimensional array holds rows and columns.

  • Data in a grid
  • Rows and columns
  • An array of arrays

Cinema seats

Two pairs of square brackets make a two dimensional array. It's really an array of rows, and each row is an array. Length gives the number of rows. Seats, zero, dot length gives the length of one row. Two indexes pick one seat, row first, then column. Nested loops visit every seat. Run it. Three rows, four seats each. Row one, seat two is taken. And the grid shows X for taken seats.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[][] seats = {
            {1, 0, 1, 1},
            {0, 0, 1, 0},
            {1, 1, 1, 1}
        };
        System.out.println("Rows: " + seats.length);
        System.out.println("Seats per row: " + seats[0].length);
        System.out.println("Row 1, seat 2: " + seats[1][2]);
        seats[1][0] = 1;
        for (int[] row : seats) {
            for (int s : row) {
                System.out.print(s == 1 ? "X " : ". ");
            }
            System.out.println();
        }
    }
}
Output
Rows: 3
Seats per row: 4
Row 1, seat 2: 1
X . X X
X . X .
X X X X

Reading grid[r][c]

The first index picks the row. The second picks the column, inside that row. Both start at zero. And the outer loop usually walks the rows, while the inner loop walks the columns.

keyvalue
grid[r]a whole row
grid[r][c]one cell
grid.lengthnumber of rows
grid[0].lengthcolumns in a row

Summary

A two dimensional array is an array of rows. Use two indexes, row then column, and nested loops. Next, common array mistakes.

Key takeaways
  • int[][] grid
  • grid[row][col]
  • Nested loops
Next up: Common Array Mistakes — traps to avoid