Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 22: Multidimensional Arrays in Java

Java for Beginners · Module 5: Data and Methods


🎯 Tables of Data

Marks of 3 students in 4 subjects, a chessboard, a seating chart, a matrix in mathematics: all of these are tables with rows and columns. A two-dimensional (2D) array stores such a table. You need two indexes to reach one value: the row, then the column.

📌 A 2D array is an array whose elements are themselves arrays. Write m[row][col] to reach one value.

1️⃣ Creating and Reading a 2D Array

int[][] m = {{1,2,3},{4,5,6}};
col 0col 1col 2
row 0123
row 1456
m[1][2] is row 1, column 2: the highlighted 6. m.length = 2 rows, m[0].length = 3 columns.

Figure 1: A 2D array is a table of rows and columns.

Program 1: Creating, reading and printing

import java.util.Arrays;

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

        for (int r = 0; r < m.length; r++) {
            for (int c = 0; c < m[r].length; c++) {
                System.out.print(m[r][c] + " ");
            }
            System.out.println();
        }

        int[][] grid = new int[3][4];
        grid[2][3] = 9;
        System.out.println(Arrays.deepToString(grid));
    }
}
🖥️ Output:
rows = 2, cols = 3
m[1][2] = 6
1 2 3
4 5 6
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 9]]
  • m.length is the number of rows. m[0].length is the number of columns in row 0.
  • Reading every element needs a nested loop (Lesson 19): the outer loop picks the row and the inner loop walks along it.
  • new int[3][4] creates 3 rows of 4 columns, all zeros.
  • Arrays.deepToString prints a 2D array. (Arrays.toString would print only the row addresses.)

2️⃣ An Array of Arrays

m ➜ [0] [1]
[0] ➜123
[1] ➜456
Java has no true 2D block. A 2D array is an array of arrays: each row is a separate array object.

Figure 2: How a 2D array is really stored.

In Java a 2D array is stored as a main array that holds references to the row arrays. This explains why each row has its own length, and why rows can be different sizes.

3️⃣ Matrix Operations

TaskPattern
Visit every elementfor r ... for c ... using m[r][c]
Row countm.length
Column count (row r)m[r].length
Print neatlyArrays.deepToString(m)
Transposet[j][i] = a[i][j]
Add two matricessum[i][j] = a[i][j] + b[i][j]

Figure 4: Everyday 2D array patterns.

Program 2: Add, multiply and transpose

import java.util.Arrays;

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

        int[][] sum = new int[2][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                sum[i][j] = a[i][j] + b[i][j];
        System.out.println("A + B = " + Arrays.deepToString(sum));

        int[][] prod = new int[2][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                for (int k = 0; k < 2; k++)
                    prod[i][j] += a[i][k] * b[k][j];
        System.out.println("A x B = " + Arrays.deepToString(prod));

        int[][] t = new int[2][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                t[j][i] = a[i][j];
        System.out.println("A transposed = " + Arrays.deepToString(t));

        int total = 0;
        for (int[] row : a)
            for (int v : row)
                total += v;
        System.out.println("sum of all elements of A = " + total);
    }
}
🖥️ Output:
A + B = [[6, 8], [10, 12]]
A x B = [[19, 22], [43, 50]]
A transposed = [[1, 3], [2, 4]]
sum of all elements of A = 10
  • Addition adds the matching positions.
  • Multiplication needs three loops. Each result cell is the sum of (row of A) × (column of B): for the top-left cell, 1×5 + 2×7 = 19.
  • Transpose swaps rows and columns: the element at row i, column j goes to row j, column i.
  • For-each over a 2D array: the outer variable is a whole row (int[] row), and the inner variable is one value.
  • When a loop body is one statement, the braces may be left out. Keeping them is safer for beginners.

4️⃣ Jagged and Higher-Dimensional Arrays

1
11
121
1331
Rows can have different lengths. This is a jagged array (here Pascal’s triangle).

Figure 3: A jagged array has rows of different lengths.

import java.util.Arrays;

public class Jagged {
    public static void main(String[] args) {
        int[][] tri = new int[4][];
        for (int r = 0; r < tri.length; r++) {
            tri[r] = new int[r + 1];
            for (int c = 0; c <= r; c++) {
                tri[r][c] = (c == 0 || c == r) ? 1 : tri[r - 1][c - 1] + tri[r - 1][c];
            }
        }
        for (int[] row : tri) {
            System.out.println(Arrays.toString(row));
        }
        System.out.println("row lengths: " + tri[0].length + ", " + tri[1].length + ", " + tri[2].length + ", " + tri[3].length);

        int[][][] cube = new int[2][3][4];
        System.out.println("3D: " + cube.length + " x " + cube[0].length + " x " + cube[0][0].length);
    }
}
🖥️ Output:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
row lengths: 1, 2, 3, 4
3D: 2 x 3 x 4
  • new int[4][] fixes only the number of rows. Each row is created later with its own length, so row r gets r + 1 columns.
  • Each Pascal’s triangle entry (except the ends) is the sum of the two above it.
  • Three or more dimensions follow the same idea: new int[2][3][4] is 2 blocks of 3 rows of 4 columns. Beyond 3D they are rarely needed.

5️⃣ Errors Beginners Meet

Row or column out of range

public class Oob2 {
    public static void main(String[] args) {
        int[][] m = new int[2][3];
        m[2][0] = 1;
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at Oob2.main(Oob2.java:4)
  • There are only rows 0 and 1. Check m.length for rows and m[r].length for columns.

Using a row that was never created

public class Npe {
    public static void main(String[] args) {
        int[][] m = new int[3][];
        m[1][0] = 5;
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.NullPointerException: Cannot store to int array because “<local1>[1]” is null
at Npe.main(Npe.java:4)
  • With new int[3][], the rows do not exist yet and are null. Create the row first: m[1] = new int[2];. (The message shows <local1> because the program was compiled without debug names. In an IDE it shows m[1].)

⚠️ Common Mistakes

MistakeProblemFix
Swapping row and column: m[col][row]Wrong element or out-of-range errorRow first, then column
Using m.length for the column countThat is the number of rowsUse m[0].length
Printing with Arrays.toString(m)Shows row addressesArrays.deepToString(m)
Using new int[3][] then writing into a rowRow is nullCreate each row first
Multiplying matrices with the wrong sizesColumns of A must equal rows of BCheck sizes first
Reusing the same loop variable in nested loopsLoops interfereUse i, j, k

❓ Frequently Asked Questions

Q1. Can rows of a 2D array have different lengths?
Yes. That is a jagged array. Create each row with its own size.

Q2. Is a 2D array stored in one block like in C?
No. In Java it is an array of row arrays, which may sit in different places in memory.

Q3. How do I read a matrix from the keyboard?
Use a nested loop with Scanner: m[i][j] = sc.nextInt(); (Lesson 10).

Q4. How many dimensions can an array have?
Up to 255 in theory, but 1, 2 and rarely 3 are used in practice.

✅ Key Takeaways

  • A 2D array is a table: m[row][col].
  • m.length = rows, m[r].length = columns of row r.
  • Use a nested loop to visit every element, or a nested for-each.
  • It is really an array of arrays, so jagged arrays are possible.
  • Print with Arrays.deepToString.
🎓 Practice questions: (1) Store marks of 3 students in 4 subjects and print each student’s total. (2) Print the diagonal of a square matrix. (3) Check whether a matrix is symmetric (equal to its transpose). (4) Print a 2D array in a spiral order. (5) Explain the difference between m.length and m[0].length.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision