Codiqo

Learn Java · lesson 28 of 61 · about 8 minutes

2D Arrays

Draw the small screen's seats: work with a grid of seats as an array of arrays.

What you'll learn

  • Create a 2D array
  • Read items with two indexes
  • Loop over rows and columns

The small screen

The cinema's small screen has 3 rows of 6 seats, and some were booked online. A grid like that is a 2D array, char[][] hall = new char[3][6]: an array of 3 rows, each an array of 6 seats. Arrays.fill sets every seat in a row to '.', each booking marks one seat with 'X', and a loop inside a loop counts the free seats.

Rows and columns

int[][] grid = {{1, 2, 3}, {4, 5, 6}}; is an array of rows. grid[1][2] is row 1, column 2 (which is 6).

  • grid.length is the number of rows
  • grid[r].length is the number of columns in row r

Reading one cell

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

Output

6 1

A game board

public class Main {
    public static void main(String[] args) {
        char[][] board = {
            {'X', 'O', 'X'},
            {' ', 'X', 'O'},
            {'O', ' ', 'X'},
        };
        for (char[] row : board) {
            System.out.println(new String(row).replace(' ', '.'));
        }
        boolean diagonal = board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X';
        System.out.println("X wins diagonally: " + diagonal);
    }
}

Output

XOX
.XO
O.X
X wins diagonally: true

Tip

new String(row) turns a char[] into a String, so a whole row prints at once.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.