Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 201 ยท Arrays

Multidimensional Arrays

Learn Java multidimensional arrays - creating 2D arrays, rows and columns, jagged arrays, nested loops over grids, printing with deepToString and matrix multiplication.

Many kinds of data come in rows and columns: a spreadsheet, a seating chart, a game board, the pixels of an image, a matrix in a math library. A plain array is a single row. To model a grid, Java lets an array hold other arrays. An array of arrays is what Java calls a two-dimensional (2D) array, and you can keep nesting for three or more dimensions.

Java doesn't have true rectangular matrices built into the language. A 2D array is literally an array whose elements are references to row arrays. That design has a nice consequence: rows can have different lengths (so-called jagged arrays). It also explains a few behaviors that confuse people who come from other languages. This lesson covers creating and indexing 2D arrays, looping through them, jagged arrays, copying pitfalls, and finishes with grid algorithms and matrix multiplication.

Creating a 2D array

The type int[][] reads "array of int[]". Create one with two sizes, rows first, then columns:

Java
int[][] seats = new int[3][4];     // 3 rows, each with 4 columns, all 0

Or fill it with a nested initializer, one inner brace pair per row:

Java
int[][] grid = {
    { 1, 2, 3 },
    { 4, 5, 6 },
};

You access an element with two indexes, grid[row][col]. The first index picks a row (an int[]), and the second picks an element in that row. Both start at 0.

Java Rows, columns and length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The key facts from that run:

  • grid.length is the number of rows; grid[r].length is the number of columns in row r.
  • grid[0] on its own is a complete int[], which you can pass to any method that takes an array.
  • Arrays.toString on a 2D array prints the row references ([[I@...). Use Arrays.deepToString to see the numbers.

How it looks in memory

new int[3][4] creates four objects: one outer array of length 3 and three row arrays of length 4. The outer array stores references to the rows, not the numbers themselves:

TEXT
grid โ”€โ”€> [ ref0 | ref1 | ref2 ]
            โ”‚      โ”‚      โ”‚
            โ”‚      โ”‚      โ””โ”€โ”€> [ 0 | 0 | 0 | 0 ]
            โ”‚      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> [ 0 | 0 | 0 | 0 ]
            โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> [ 0 | 0 | 0 | 0 ]

Keeping this picture in mind explains everything else in this lesson: jagged rows, null rows, and why copying a 2D array is harder than it looks.

Looping over a grid

Nested loops are the natural fit: the outer loop picks a row, the inner loop walks the columns of that row. Use grid[row].length (not grid[0].length) in the inner condition so the loop also works for jagged arrays:

Java Row totals, column totals and a formatted table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The row total resets for every row, so it's declared inside the outer loop. The column totals need one slot per column and survive across all rows, so they live in an array declared before both loops. Name the indexes after what they mean (store, q, or row, col); a nested loop full of i and j is easy to get backward.

When you only read values, nested for-each loops are shorter. The outer loop variable is a whole row:

Java
int sum = 0;
for (int[] row : sales) {
    for (int value : row) {
        sum += value;
    }
}

Row-major order and speed

The examples walk row by row, with the column index changing fastest. That's called row-major order, and it's also the fast order in Java: the elements of one row sit next to each other in memory, so the CPU cache works in your favor. Walking column by column (for col { for row { ... } }) jumps between different row arrays on every step. For small grids you won't notice; for a 4,000 ร— 4,000 image, row-major can be several times faster.

Jagged arrays

Because each row is a separate array, rows don't have to be the same length. You can leave the second size out of new and create each row yourself:

Java A jagged triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This builds Pascal's triangle, where each entry is the sum of the two above it. Each row is exactly as long as it needs to be, so no space is wasted.

With new long[rows][], the outer array is created but every row is null until you assign one. Accessing pascal[0][0] before that throws a NullPointerException. Only the first size can be given alone: new int[][5] is a compile error, because Java has to create the outer array first.

Jagged arrays are natural for data with uneven rows: lines of text split into words, the days in each month, a graph's adjacency lists, or a lower-triangular distance table. Initializers can be jagged too:

Java
String[][] teams = {
    { "Ana", "Bo" },
    { "Cyd" },
    { "Dee", "Eli", "Fay", "Gus" },
};

Copying a 2D array

Recall the memory picture: the outer array holds references to rows. So clone() on a 2D array copies only the outer array; the copy's rows are the same row objects:

Java clone() is shallow for 2D arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

To get an independent copy, clone each row, as the loop does (Arrays.copyOf(board[r], board[r].length) works too). The same reasoning applies to comparing: Arrays.equals on 2D arrays compares row references, while Arrays.deepEquals compares the actual numbers. The Arrays Class covers both.

A related trap: Arrays.fill(grid, row) with one row array puts the same row in every slot, so setting grid[0][0] changes "every" row. Create a new array for each row instead.

Working with grids

Game boards and maps are 2D arrays of char or an enum. Two techniques come up constantly: checking bounds before you look at a neighbor, and using direction arrays to visit neighbors without eight copies of the same code.

Java Minesweeper-style neighbor counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

"..*..".toCharArray() turns each string into a row of characters, which makes small boards easy to type. The bounds check must come before the access; thanks to the short-circuit && (see Comparison and Logical Operators), field[nr][nc] is never evaluated for a neighbor outside the board. Without that check, cells on the edges would throw ArrayIndexOutOfBoundsException.

You'll build a full game on a 2D board in Project: Tic-Tac-Toe.

Matrix multiplication

In math, multiplying an n ร— m matrix A by an m ร— p matrix B gives an n ร— p matrix C, where each entry is the dot product of a row of A and a column of B:

C[i][j] = A[i][0]ยทB[0][j] + A[i][1]ยทB[1][j] + ... + A[i][m-1]ยทB[m-1][j]

That's three nested loops. The number of columns of A must equal the number of rows of B; otherwise the product isn't defined.

Java Multiply two matrices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The result is [58, 64] and [139, 154]. For example, the top-left entry is 1ยท7 + 2ยท9 + 3ยท11 = 58. The loop does rows ร— cols ร— shared multiplications, so doubling every dimension makes it eight times slower. Real numeric code uses specialized libraries that reorder these loops for the cache and use multiple cores, but the triple loop is exactly what they compute.

A simpler matrix operation is the transpose, which flips rows and columns. Note how the result's dimensions are swapped:

Java
int[][] t = new int[a[0].length][a.length];
for (int r = 0; r < a.length; r++) {
    for (int c = 0; c < a[r].length; c++) {
        t[c][r] = a[r][c];
    }
}

More matrix programs

Most matrix exercises are variations on four ideas: loop over every cell, loop over one row or column, use i == j for the main diagonal and i + j == n - 1 for the anti-diagonal, and build a new array rather than changing the input while you read it.

The program below works on one 3x3 matrix and shows, in order: the trace (sum of the main diagonal), the anti-diagonal sum, the Frobenius "normal" (square root of the sum of squares), the determinant by cofactor expansion, the boundary elements, a 90-degree clockwise rotation, swapping the first and last rows and columns, sorting each column independently, four kinds of equality and finally a spiral fill.

Java Matrix programs: trace, determinant, rotate, spiral

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Things worth remembering:

  • Rotation by 90 degrees clockwise sends the element at [r][c] to [c][n - 1 - r]. Writing into a second array is the simple way; rotating in place needs a transpose followed by reversing every row.
  • Determinant. The recursive version expands along the first row: each element is multiplied by the determinant of the smaller matrix left after removing its row and column, with alternating signs. It is O(n!) and fine for tiny matrices; real code uses Gaussian elimination.
  • Copying before changing. s[r] = a[r].clone() copies each row. Copying only the outer array (a.clone()) would share the rows and the swap would damage the original (see Copying a 2D array).
  • Equality. == compares references, equals on an array is also reference identity, Arrays.equals compares the rows as objects (so it is false for 2D arrays), and only Arrays.deepEquals compares the contents.
  • Spiral. Keep four moving borders (top, bottom, left, right), fill one side, shrink that border and repeat; the extra conditions on the last two loops stop a single leftover row or column from being filled twice.

Three or more dimensions

The same idea extends to any depth. int[][][] cube = new int[2][3][4]; is an array of 2 grids, each with 3 rows of 4 columns, accessed as cube[layer][row][col]. Three dimensions are occasionally useful (frames of a video, a building's floors and rooms), but beyond that, code gets hard to read quickly. Usually a class or a record describes the data better than a fourth pair of brackets.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For int[][] m = new int[3][5];, what are m.length and m[0].length?

    The first size is the number of rows (the outer array's length) and the second is the length of each row.
  2. 2. What does int[][] j = new int[2][]; IO.println(j[1]); print?

    Leaving out the second size creates the outer array only. Its elements are references to rows, and they start as null until you assign row arrays.
  3. 3. What is printed? int[][] a = {{1, 2}, {3, 4}}; int[][] b = a.clone(); b[1][0] = 9; IO.println(a[1][0]);

    clone() copies only the outer array, so a and b share the same row arrays. Changing b[1][0] changes the row that a[1] also points to.
  4. 4. Multiplying a 4 x 2 matrix by a 2 x 6 matrix gives a matrix of which size?

    The inner dimensions (2 and 2) match, so the product exists, and it takes its rows from the first matrix and its columns from the second.
  5. 5. Which method prints the numbers inside a 2D int array?

    Arrays.toString only formats the outer array, whose elements are row references. deepToString descends into nested arrays and prints their contents.

Summary

  • A 2D array is an array of arrays: int[][] g = new int[rows][cols] or a nested initializer { { ... }, { ... } }.
  • g[r][c] selects row r, then column c; g.length counts rows and g[r].length counts the columns of row r.
  • Loop with nested loops (row outer, column inner) and use g[r].length in the inner condition so jagged rows work.
  • Jagged arrays have rows of different lengths; new int[n][] creates n null rows that you fill yourself.
  • clone() and Arrays.equals are shallow for 2D arrays; clone each row for a deep copy and use deepEquals/deepToString.
  • Check bounds before reading neighbors, and use direction arrays to keep grid code short.
  • Matrix multiplication is a triple loop; the inner dimensions must match.

Next: The Arrays Class, where you'll sort, search, fill, compare and stream arrays with one method call each.