Enhanced For Loops Over 2D Arrays

Part of: 2D Array

The For-Each Over a Grid The enhanced for loop (for-each) also works on 2D arrays, but you must remember the array-of-arrays structure. The outer for-each gives you each row , which is itself a 1D array. A second, inner for-each then walks the elements of that row. The Critical Type Detail The outer loop variable must be declared as a 1D array of the element type: - For int[][], the outer variable is int[] row and the inner is int value. - For String[][], the outer variable is String[] row and the inner is String s. Forgetting the brackets on the outer variable is the most common mistake. When to Use For-Each The enhanced for loop is ideal when you only need to read every cell, because it is concise and avoids index bookkeeping. However, it has real limits: - You cannot know the current row or column index inside the loop. - You cannot reliably write back into the array through the loop variable for primitives, value = value 2; only changes the copy. Read vs. Modify If you need indices, or you must change the contents, fall back to indexed nested loops with grid[r][c]. Use the enhanced for loop for read-only passes such as summing, counting, searching for a value, or printing. Know

Challenge: Count Matches with For-Each