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).
// 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);
}
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);
}
}
While elegant, the for-each loop is not a universal replacement for the standard for loop:
item = 0; does not modify the underlying array).0 to length - 1.collection.remove() inside a for-each loop throws ConcurrentModificationException.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(); ... }
Now let us explore unconditional jump statements: Break, Continue, and Labeled Loops. Proceed to: Java Break & Continue →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Indexed traversal alternative.
Array structures in Java.
Traversing lists and sets.
Fail-fast iterator mechanics.