Java Enhanced For-Each Loop: Iterating Arrays and Collections

Introduced in Java 5, the Enhanced For-Each Loop offers a streamlined, error-proof syntax designed specifically to traverse arrays and any object implementing the java.lang.Iterable interface (such as ArrayList, HashSet, LinkedList).

Syntax Comparison: Traditional For vs. Enhanced For

// Traditional For Loop (Requires manual index counter & bounds check):
for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

// Enhanced For-Each Loop (Eliminates off-by-one errors & boilerplate):
for (ElementType variableName : arrayOrCollection) {
    System.out.println(variableName);
}

Code Example: Traversing Arrays & Collections

import java.util.List;
import java.util.ArrayList;

public class ForEachDemo {
    public static void main(String[] args) {
        // 1. Iterating an Array of Strings
        String[] technologies = { "Java", "Spring Boot", "Docker", "Kubernetes" };
        System.out.println("--- Array Traversal ---");
        for (String tech : technologies) {
            System.out.println("Tech: " + tech);
        }

        // 2. Iterating a Collection (List)
        List<Integer> scores = new ArrayList<>();
        scores.add(88);
        scores.add(94);
        scores.add(76);

        int total = 0;
        for (int score : scores) { // Autounboxing from Integer to int
            total += score;
        }
        System.out.println("
Total Score: " + total);
    }
}

Limitations of the For-Each Loop (When NOT to Use It)

While elegant, the for-each loop is not a universal replacement for the standard for loop:

  • No Index Access: You cannot determine the current index position (e.g. you cannot print "Item at index 3").
  • No In-Place Modification: You cannot overwrite array elements (e.g. item = 0; does not modify the underlying array).
  • No Reverse Traversal: Traversal is strictly forward from element 0 to length - 1.
  • No Structural Deletion: Calling collection.remove() inside a for-each loop throws ConcurrentModificationException.

University Exam Corner (BCA / B.Sc CS)

Exam Question: "Under the hood, how does the JVM execute a for-each loop on a Collection?"

Answer: The javac compiler translates the for-each loop into an explicit Iterator loop. For example, for(String s : list) is compiled into:
for (Iterator<String> it = list.iterator(); it.hasNext(); ) { String s = it.next(); ... }

Next Step

Now let us explore unconditional jump statements: Break, Continue, and Labeled Loops. Proceed to: Java Break & Continue →

Frequently Asked Questions (FAQ)

Q1. What is the enhanced for-each loop in Java?
Introduced in Java 5, the enhanced for-each loop provides a simplified, read-only iteration syntax for traversing sequential data structures (arrays and any class implementing java.lang.Iterable) without manual index management.
Q2. Can I modify array elements inside an enhanced for-each loop?
No! The iteration variable holds a local copy of each element. Reassigning the iteration variable (e.g. x = 100) only changes the local loop variable, leaving the original array or collection untouched.
Q3. Can I remove elements from an ArrayList during for-each iteration?
No! Modifying an ArrayList (using list.remove()) inside a for-each loop throws a ConcurrentModificationException because for-each uses an internal fail-fast Iterator. Use Iterator.remove() or list.removeIf() instead.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

Standard For Loop →

Indexed traversal alternative.

Java Arrays →

Array structures in Java.

Collections Framework →

Traversing lists and sets.

Java Iterators →

Fail-fast iterator mechanics.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!