Enhanced for Loop with 2D Arrays
You'll learn how to use the enhanced for loop (for-each) to simplify iteration over two-dimensional arrays without manually managing row and column indices.
The Core Idea
When working with 2D arrays, you previously needed nested traditional for loops with index variables to visit every element. The enhanced for loop makes this cleaner: the outer loop iterates over each row (which is itself a 1D array), and the inner loop iterates over each element within that row.
Think of it like opening boxes within boxes: the outer loop hands you one box (row) at a time, and the inner loop lets you examine each item (element) inside that box.
Syntax with 2D Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Enhanced for loop syntax
for (int[] row : matrix) { // Outer loop: each row
for (int element : row) { // Inner loop: each element in row
System.out.print(element + " ");
}
System.out.println();
}
Notice that row is an int[] (a one-dimensional array), because each row in a 2D array is itself an array. Then the inner loop treats row just like any 1D array.
When to Use It
This approach is perfect when you need to read every element but don't need to know the row or column index. For jagged arrays, it handles varying row lengths automatically without extra checks.
Limitations Reminder
Remember: you cannot modify which row or element you're looking at, and you don't have access to indices. If you need to know positions or change array structure, use traditional nested loops.
Key Takeaway: Use nested enhanced for loops with 2D arrays to cleanly iterate over all elements when indices aren't needed—the outer loop provides each row, the inner loop provides each element.