Two-Dimensional Arrays

An array of arrays: rows and columns. Mark cinema seats and count them with nested loops.

Java · beginner · 8 min · 23 steps · free

What you'll learn

TwoDArraysDemo.java

public class TwoDArraysDemo {
    public static void main(String[] args) {
        int[][] seats = new int[2][3];
        seats[0][1] = 1;
        seats[1][2] = 1;
        int taken = 0;
        for (int row = 0; row < seats.length; row++) {
            for (int col = 0; col < seats[row].length; col++) {
                taken += seats[row][col];
            }
        }
        System.out.println("Seats taken: " + taken);
    }
}

Step by step

  1. new int[2][3] makes 2 rows of 3 seats. In memory it is one array holding two row arrays.
  2. Row 0, column 1: a seat is taken.
  3. Row 1, column 2.
  4. taken is created on the stack with the value 0.
  5. seats.length is the number of rows: 2.
  6. seats[row].length is the number of columns in this row: 3.
  7. Line runs: taken += seats[row][col].
  8. col changes from 0 to 1.
  9. taken changes from 0 to 1.
  10. col changes from 1 to 2.
  11. Line runs: taken += seats[row][col].
  12. col goes out of scope and disappears.
  13. row changes from 0 to 1.
  14. col is created on the stack with the value 0.
  15. Line runs: taken += seats[row][col].
  16. col changes from 0 to 1.
  17. Line runs: taken += seats[row][col].
  18. col changes from 1 to 2.
  19. taken changes from 1 to 2.
  20. col goes out of scope and disappears.
  21. row goes out of scope and disappears.
  22. It prints Seats taken: 2.
  23. 2 seats taken. A 2D array is an array of rows; the outer loop picks a row and the inner loop walks its columns.

Common mistakes

Best practices

Key takeaways

Check yourself

int[][] g = new int[3][4]; g.length is?

Answer: 3. The outer array has 3 rows.

g[1][2] means?

Answer: Row 1, column 2. Row first, then column.

·

More in Arrays and Text