Enhanced for-each Loop
The enhanced for-each loop (also called the for-each loop) is a simplified looping construct introduced in Java 5. It is used to iterate over arrays and collections without managing indexes explicitly. This loop improves readability, safety, and maintainability, especially when index access is not required.
What Is the Enhanced for-each Loop?
- Used to iterate over arrays and collections
- Eliminates index handling
- Executes sequentially from first to last element
- Read-only access to elements
Basic Syntax
for (dataType variable : collectionOrArray) {
// code to execute
}
Simple Example with Array
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
Output:
10
20
30
40
Example with String Array
String[] languages = {"Java", "Python", "C"};
for (String lang : languages) {
System.out.println(lang);
}
Example with Collections
Listnames = new ArrayList<>(); names.add("Alice"); names.add("Bob"); for (String name : names) { System.out.println(name); }
Execution Flow
- Loop variable gets one element per iteration
- Loop continues until all elements are processed
- No index variable involved
When to Use Enhanced for-each Loop
- Traversing arrays
- Reading elements from collections
- When index value is not required
- When no modification of structure is needed
When NOT to Use Enhanced for-each Loop
- When you need:
- Index access
- Reverse iteration
- Element removal during iteration
- Conditional skipping based on index
// ❌ Cannot remove elements safely
for (String s : list) {
list.remove(s);
}
Enhanced for-each vs Traditional for Loop
| Feature | Enhanced for-each | Traditional for |
|---|---|---|
| Index Access | ❌ No | ✅ Yes |
| Readability | High | Medium |
| Modification | ❌ No | ✅ Yes |
| Reverse Loop | ❌ No | ✅ Yes |
| Best For | Traversal | Control-based logic |
Enhanced for-each with 2D Arrays
int[][] matrix = {
{1, 2},
{3, 4}
};
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
Common Beginner Mistakes
- Expecting index value
- Trying to modify array/collection structure
- Confusing with iterator-based loops
- Using for-each when index is required
Interview-Ready Answers
Short Answer
The enhanced for-each loop is used to iterate over arrays and collections without using indexes.
Detailed Answer
The enhanced for-each loop simplifies iteration by automatically accessing each element in a collection or array. It improves readability but does not allow index-based access or structural modification.
Key Takeaway
The enhanced for-each loop is ideal for simple traversal. Use it when you want clean, readable code and do not need index control.