Advertisement
Intermediate Java, Arrays & Multidimensional Arrays

How do you correctly iterate a 2D array using both traditional indexed for-loops and the enhanced for-each loop, and when is each approach preferable?

Short answer

The enhanced for-each loop (for (int[] row : matrix) { for (int value : row) { ...

Save Java mock interview
Advertisement
AModel answer
The enhanced for-each loop (for (int[] row : matrix) { for (int value : row) { ... } }) is more concise and less error-prone for simple read-only traversal, avoiding index-related bugs entirely, but doesn't give you direct access to the current index (needed if you must modify elements in place, or need to know row/column position for logic); the traditional indexed loop is required whenever you need to mutate elements, need the index for other computation, or need to iterate multiple related arrays in lockstep using a shared index.
int[][] matrix = {{1,2,3},{4,5,6}};

// for-each: simpler for read-only traversal
for (int[] row : matrix) {
    for (int value : row) {
        System.out.print(value + " ");
    }
}

// indexed: needed when mutating in place or requiring the index
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        matrix[i][j] *= 2;  // requires index-based access to mutate
    }
}
Real-world example
A matrix-doubling utility uses an indexed loop specifically because it needs to write back into each cell (matrix[i][j] *= 2), whereas a separate read-only matrix-printing utility uses the simpler for-each syntax since it never needs to mutate or track explicit indices.
Likely follow-ups
  • Why can't you assign to the for-each loop variable to modify the underlying array element?
  • What's the subtle bug risk of using the same variable name for both the outer and inner loop's for-each variable?
Related topics