Syllabus / Java / Phase 2: Control Flow & Data (Days 6–10)
Intermediate

Multidimensional Arrays

📂 Phase 2: Control Flow & Data (Days 6–10) · Java

A 2D array is essentially an "array of arrays" — useful for representing grids, matrices, and tabular data such as a seating chart or a game board.

Declaring a 2D Array

// Direct initialization
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Declare with fixed dimensions, fill later
int[][] grid = new int[3][3]; // 3 rows, 3 columns

Understanding Rows and Columns

  • matrix.length — the number of rows (the outer array's size)
  • matrix[0].length — the number of columns (the first inner array's size)
  • matrix[row][col] — accesses the element at that row and column
System.out.println(matrix[1][2]); // 6 — row index 1, column index 2

Traversing a 2D Array with Nested Loops

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

for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        System.out.print(matrix[row][col] + " ");
    }
    System.out.println(); // newline after each row
}
// Output:
// 1 2 3
// 4 5 6
// 7 8 9

The outer loop walks through each row; the inner loop walks through every column within that row. This is called row-major order traversal — the most common pattern for 2D array problems.

Calculating a Total Across a 2D Array

int total = 0;
for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        total += matrix[row][col];
    }
}
System.out.println("Sum: " + total); // 45

Printing with Arrays.deepToString()

import java.util.Arrays;
System.out.println(Arrays.deepToString(matrix));
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Interview tip: A common trick question is "what does matrix[0].length return?" — it returns the number of columns in row 0, not the total number of elements in the matrix.