What is a 2D Array?

A 2D array is an array whose elements are themselves arrays.

Think of a 2D array as a table, spreadsheet, seating chart, or game board. Instead of storing data in a single line like a 1D array, a 2D array organizes data into rows and columns.

Example: Student Grades

Student Quiz 1 Quiz 2 Quiz 3
Alice 90 85 92
Bob 78 88 81
Cara 95 91 97

This information can be stored in Java as:

int[][] grades = {
    {90, 85, 92},
    {78, 88, 81},
    {95, 91, 97}
};

Each row stores information about one student, while each column stores information about one quiz.

A 2D array requires two indices:

grades[row][column]

The first index selects a row.

The second index selects a column.

For example:

grades[1][2]
  • Row 1 β†’ {78, 88, 81}
  • Column 2 β†’ 81

Result:

81

Why Use 2D Arrays?

A 1D array stores information in a single list:

String[] students = {
    "Alice",
    "Bob",
    "Cara"
};

This works when there is only one category of information.

However, many real-world situations require data to be organized into rows and columns.

Examples include:

  • Classroom seating charts
  • Monthly calendars
  • Game boards
  • Student gradebooks
  • Tournament brackets
  • Pixel locations in an image

A 2D array allows related information to be grouped together in a structured way.


Visualizing Rows and Columns

Consider the following seating chart:

String[][] seating = {
    {"Ava", "Ben", "Chris"},
    {"Diana", "Ethan", "Faith"},
    {"Grace", "Henry", "Ivy"}
};
            Column
          0      1       2

Row 0   Ava    Ben    Chris
Row 1   Diana  Ethan  Faith
Row 2   Grace  Henry  Ivy

Code Runner Challenge

Predict the name at [0][1], [2][0], and [1][2] before you run it

View IPYNB Source
// CODE_RUNNER: Predict the name at [0][1], [2][0], and [1][2] before you run it
public class SeatingChart {
    public static void main(String[] args) {
        String[][] seating = {
            {"Ava", "Ben", "Chris"},
            {"Diana", "Ethan", "Faith"},
            {"Grace", "Henry", "Ivy"}
        };

        // Row first, then column.
        System.out.println(seating[0][1]); // expected: Ben
        System.out.println(seating[2][0]); // expected: Grace
        System.out.println(seating[1][2]); // expected: Faith
    }
}
SeatingChart.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Declaring a 2D Array

Declaring a 2D array is very similar to declaring a 1D array.

1D Array

int[] scores;

2D Array

int[][] scores;

The extra pair of brackets indicates that each element is itself an array.

Examples:

int[][] numbers;
String[][] names;
Student[][] roster;

Initializing a 2D Array

Method 1: Initialize with Values

int[][] grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

Method 2: Create an Empty Grid

int[][] grid = new int[3][3];

This creates a 3-row by 3-column array.

All integer values start as 0.

0 0 0
0 0 0
0 0 0

Accessing Elements

The general format is:

array[row][column]

Example:

Code Runner Challenge

Predict what numbers[2][1] prints before you run it. Remember: row first, then column

View IPYNB Source
// CODE_RUNNER: Predict what numbers[2][1] prints before you run it. Remember: row first, then column
public class AccessElement {
    public static void main(String[] args) {
        int[][] numbers = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        System.out.println(numbers[2][1]);
    }
}
AccessElement.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Step-by-step:

  1. Find row 2 β†’ {7, 8, 9}
  2. Find column 1
  3. Return the value

Output:

8

Updating Elements

Arrays are mutable, meaning their values can be changed after creation.

Example:

Code Runner Challenge

Predict which number changes, then run it and compare the two grids

View IPYNB Source
// CODE_RUNNER: Predict which number changes, then run it and compare the two grids
public class UpdateElement {
    static void printGrid(int[][] grid) {
        for (int[] row : grid) {
            System.out.println(java.util.Arrays.toString(row));
        }
    }

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

        System.out.println("Before:");
        printGrid(board);

        board[1][1] = 100;

        System.out.println("After board[1][1] = 100:");
        printGrid(board);
    }
}
UpdateElement.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Can you notice what changed?

Only the specified location changes.

The rest of the array remains unchanged.


2D Arrays with Objects

2D arrays can store objects just like 1D arrays.

Example:

Student[][] classroom = new Student[3][3];

Each location can store a reference to a Student object.

classroom[0][0] = new Student("Alice", 16);
classroom[1][2] = new Student("Bob", 17);

Accessing methods works the same way:

System.out.println(classroom[0][0].getName());

Output:

Alice

This allows complex information to be organized into rows and columns.


HACK: AP CSA 2D Arrays

Part 1: AP CSA Multiple Choice

5 questions. Use the tabs to move between them, and check an answer as many times as you need. Each check saves that answer, and your last saved answers are sent when you click Submit Code at the bottom of this page.

MCQ 4.11

Check each answer as many times as you need. Your last saved answers are the ones submitted.


Part 2: Representing your Group

Create a 2D array containing the members of your group.

Requirements:

  • Each row represents your group of 2 or 3.
  • Each row represents a subgroup within your larger group.
  • Make sure every member of your group is in the array.
  • Add comments explaining what each subgroup represents.

Code Runner Challenge

Replace the names with your group, add a comment for each subgroup, then run it

View IPYNB Source
// CODE_RUNNER: Replace the names with your group, add a comment for each subgroup, then run it
public class GroupRoster {
    public static void main(String[] args) {
        String[][] groups = {
            {"Alice", "Bob", "Cara"},      // TODO: subgroup 1 - what does it represent?
            {"David", "Emma", "Frank"},    // TODO: subgroup 2
            {"Grace", "Henry", "Isabella"} // TODO: subgroup 3
        };

        for (int row = 0; row < groups.length; row++) {
            System.out.println("Subgroup " + row + ": " + java.util.Arrays.toString(groups[row]));
        }
    }
}
GroupRoster.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Reflection Questions:

  1. Why is a 2D array better than a 1D array for this situation?
  2. Which index represents the row?
  3. Which index represents the column?
  4. What changes would need to be made if each subgroup had 4 students instead of 3?

Submit Assignment

Choose what to hand in: click Add to submission on each runner you want graded (hacks, popcorn hacks), and save it. Leaving out practice runners does not lower your grade, but a required hack you leave out is graded as missing. Your selection is sent as a Gist for automatic review.

    Need to update a submission later? Open the submissions dashboard.