0
0
JavaHow-ToBeginner · 3 min read

How to Iterate 2D Array in Java: Syntax and Examples

To iterate a 2D array in Java, use nested for loops where the outer loop goes through rows and the inner loop goes through columns. Access each element with array[row][column] inside the loops.
📐

Syntax

Use two nested for loops: the outer loop iterates over rows, and the inner loop iterates over columns. Access elements with array[i][j].

  • i: index for rows
  • j: index for columns
  • array[i][j]: element at row i and column j
java
for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array[i].length; j++) {
        // Access element
        System.out.println(array[i][j]);
    }
}
💻

Example

This example shows how to print all elements of a 2D integer array using nested loops.

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

        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers[i].length; j++) {
                System.out.print(numbers[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output
1 2 3 4 5 6 7 8 9
⚠️

Common Pitfalls

Common mistakes include:

  • Using the wrong loop limits, like array.length for both loops, which fails if rows have different lengths.
  • Confusing row and column indexes.
  • Not initializing the 2D array properly before iterating.

Always use array[i].length for the inner loop to handle uneven rows safely.

java
int[][] arr = {{1, 2}, {3, 4, 5}};

// Wrong: assumes all rows have same length
for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr.length; j++) { // should be arr[i].length
        System.out.print(arr[i][j] + " ");
    }
    System.out.println();
}

// Right:
for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        System.out.print(arr[i][j] + " ");
    }
    System.out.println();
}
📊

Quick Reference

  • Use array.length for number of rows.
  • Use array[i].length for number of columns in row i.
  • Access elements with array[i][j].
  • Nested loops are needed to visit every element.

Key Takeaways

Use nested for loops to iterate rows and columns of a 2D array in Java.
Always use array[i].length for the inner loop to handle rows with different lengths.
Access elements with array[i][j] inside the loops.
Avoid using the same length for both loops if the 2D array is jagged.
Initialize your 2D array properly before iterating.