Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 04 / Topic 3 of 10

Two-dimensional arrays: a grid of values

A 2D array is an array of arrays: a grid with rows and columns. int[][] grid is "an array, where each slot holds another int[]." Walk it with nested loops: the outer loop picks the row, the inner loop walks that row's columns.

Think of a shop's weekly sales sheet: one row per item, one column per day.

class TwoDArrays {
    public static void main(String[] args) {
        // rows = items, columns = days (Mon..Sun): a grid of units sold
        int[][] unitsSold = {
            {5, 3, 6, 2, 8, 10, 7},   // Rice packets
            {2, 1, 0, 3, 4, 6, 5},    // Dal packets
            {9, 7, 8, 6, 10, 12, 11}  // Milk packets
        };
        String[] items = {"Rice", "Dal", "Milk"};
        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

        System.out.println("Rows (items): " + unitsSold.length);
        System.out.println("Columns (days): " + unitsSold[0].length);

        // row totals: how much of each item sold this week
        for (int row = 0; row < unitsSold.length; row++) {
            int rowTotal = 0;
            for (int col = 0; col < unitsSold[row].length; col++) {
                rowTotal += unitsSold[row][col];
            }
            System.out.println(items[row] + " sold this week: " + rowTotal);
        }

        // column totals: how much sold in total on each day
        for (int col = 0; col < days.length; col++) {
            int colTotal = 0;
            for (int row = 0; row < unitsSold.length; row++) {
                colTotal += unitsSold[row][col];
            }
            System.out.println(days[col] + " total: " + colTotal);
        }
    }
}

Output (examples/02_two_d_arrays.java):

Rows (items): 3
Columns (days): 7
Rice sold this week: 41
Dal sold this week: 21
Milk sold this week: 63
Mon total: 16
Tue total: 11
Wed total: 14
Thu total: 11
Fri total: 22
Sat total: 28
Sun total: 23

unitsSold.length is the number of rows; unitsSold[row].length is the number of columns in that row. In this example every row happens to have 7 columns, but Java does not force that — each row is its own independent array, so rows can have different lengths if you build them that way (a "jagged" array). That's rare in practice; most 2D arrays you write will be rectangular, like this sales grid.

Full program: examples/02_two_d_arrays.java.

Done here? The practice set for Part 4 — including the solutions — is on the part page.

Search the guide