Enhanced for Loop

for-each loop for collections and arrays

Interview Relevant: Know when to use enhanced for vs traditional for
5 min read

The Enhanced for Loop (for-each)

Introduced in Java 5, the enhanced for loop provides a cleaner, more readable way to iterate over arrays and collections without managing an index.

Syntax

for (Type element : arrayOrCollection) {
    // use element
}

āœ“ Benefits: No index management, no off-by-one errors, cleaner syntax, and works with any Iterable.

Limitations

  • Cannot modify the collection during iteration
  • No access to current index
  • Forward-only traversal
  • Cannot skip elements

āš ļø Important: Modifying the collection inside enhanced for (except via iterator.remove()) throws ConcurrentModificationException!

Code Examples

Comparing traditional vs enhanced for loop

java
1// Array iteration
2int[] numbers = {1, 2, 3, 4, 5};
3
4// Traditional for loop
5for (int i = 0; i < numbers.length; i++) {
6    System.out.println(numbers[i]);
7}
8
9// Enhanced for loop (cleaner!)
10for (int num : numbers) {
11    System.out.println(num);
12}
13
14// String array
15String[] fruits = {"Apple", "Banana", "Cherry"};
16for (String fruit : fruits) {
17    System.out.println(fruit);
18}

Enhanced for with various collection types

java
1// With Collections
2List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
3
4for (String name : names) {
5    System.out.println("Hello, " + name);
6}
7
8// With Set (unordered)
9Set<Integer> uniqueNumbers = new HashSet<>(Arrays.asList(3, 1, 4, 1, 5, 9));
10for (int num : uniqueNumbers) {
11    System.out.println(num);  // Order not guaranteed
12}
13
14// With Map (using entrySet)
15Map<String, Integer> ages = new HashMap<>();
16ages.put("Alice", 25);
17ages.put("Bob", 30);
18
19for (Map.Entry<String, Integer> entry : ages.entrySet()) {
20    System.out.println(entry.getKey() + ": " + entry.getValue());
21}

Nested enhanced for loops for 2D arrays

java
1// 2D Array traversal
2int[][] matrix = {
3    {1, 2, 3},
4    {4, 5, 6},
5    {7, 8, 9}
6};
7
8for (int[] row : matrix) {
9    for (int cell : row) {
10        System.out.print(cell + " ");
11    }
12    System.out.println();
13}
14
15// Sum all elements
16int sum = 0;
17for (int[] row : matrix) {
18    for (int val : row) {
19        sum += val;
20    }
21}
22System.out.println("Sum: " + sum);  // 45

When to use traditional for instead

java
1// When NOT to use enhanced for
2
3// Need index? Use traditional for
4String[] items = {"A", "B", "C"};
5for (int i = 0; i < items.length; i++) {
6    System.out.println("Index " + i + ": " + items[i]);
7}
8
9// Need to modify array? Use traditional for
10int[] values = {1, 2, 3, 4, 5};
11for (int i = 0; i < values.length; i++) {
12    values[i] *= 2;  // Doubles each value
13}
14
15// Enhanced for CANNOT modify array!
16for (int v : values) {
17    v *= 2;  // This doesn't modify the array!
18}
19
20// Need to remove elements? Use Iterator
21List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
22Iterator<Integer> it = list.iterator();
23while (it.hasNext()) {
24    if (it.next() % 2 == 0) {
25        it.remove();  // Safe removal
26    }
27}

Use Cases

  • Reading all elements from array/collection
  • Performing operation on each element
  • Searching for an element
  • Calculating aggregate values (sum, max, min)
  • Processing stream of data
  • Displaying collection contents

Common Mistakes to Avoid

  • Trying to modify collection during iteration
  • Expecting to change array values through loop variable
  • Using when index is needed
  • Using when you need to iterate backwards
  • ConcurrentModificationException from collection modification
  • Confusing element variable with index