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.
Enhanced for-each Loop Examples
1. Basic Enhanced for-each Loop (Array)
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}
Explanation
- Iterates over each element in the array.
- No index management required.
- Output: 10 20 30
2. Enhanced for-each Loop with String Array
String[] names = {"Java", "Python", "C++"};
for (String name : names) {
System.out.println(name);
}
Explanation
- Iterates over String elements.
- Read-only access to elements.
3. Enhanced for-each Loop with Conditional Logic
int[] nums = {1, 2, 3, 4, 5};
for (int n : nums) {
if (n % 2 == 0) {
System.out.println(n);
}
}
Explanation
- Prints only even numbers.
- Conditions are allowed inside for-each.
4. Enhanced for-each Loop with break
int[] nums = {5, 10, 15, 20};
for (int n : nums) {
if (n == 15) {
break;
}
System.out.println(n);
}
Explanation
- Loop stops when 15 is encountered.
- Output: 5 10
5. Enhanced for-each Loop with continue
int[] nums = {1, 2, 3, 4, 5};
for (int n : nums) {
if (n == 3) {
continue;
}
System.out.println(n);
}
Explanation
- Skips only the value 3.
- Output: 1 2 4 5
6. Enhanced for-each Loop over List
import java.util.*; Listlist = Arrays.asList("A", "B", "C"); for (String s : list) { System.out.println(s); }
Explanation
- Works with all Iterable collections.
- Cleaner than index-based loops.
7. Enhanced for-each Loop with Set
import java.util.*; Setset = new HashSet<>(Arrays.asList(10, 20, 30)); for (int n : set) { System.out.println(n); }
Explanation
- Order is not guaranteed.
- Common for unique value traversal.
8. Enhanced for-each Loop with Map (entrySet)
import java.util.*; Mapmap = new HashMap<>(); map.put("A", 1); map.put("B", 2); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); }
Explanation
- Recommended way to iterate maps.
- Accesses both key and value.
9. Enhanced for-each Loop with Map (keySet)
import java.util.*; Mapmap = Map.of("US", "USA", "IN", "India"); for (String key : map.keySet()) { System.out.println(key); }
Explanation
- Iterates only over keys.
- Values accessed separately if needed.
10. Enhanced for-each Loop with Map (values)
import java.util.*; Mapmap = Map.of("A", "Apple", "B", "Ball"); for (String value : map.values()) { System.out.println(value); }
Explanation
- Iterates only over values.
- Useful when keys are not required.
11. Enhanced for-each Loop for 2D Array
int[][] matrix = {
{1, 2},
{3, 4}
};
for (int[] row : matrix) {
for (int val : row) {
System.out.println(val);
}
}
Explanation
- Outer loop iterates rows.
- Inner loop iterates columns.
12. Enhanced for-each Loop with Objects
class Student {
String name;
Student(String name) {
this.name = name;
}
}
Student[] students = {
new Student("John"),
new Student("Alice")
};
for (Student s : students) {
System.out.println(s.name);
}
Explanation
- Used heavily in real-world applications.
- Iterates over object references.
13. Enhanced for-each Loop – Read-Only Limitation
int[] nums = {1, 2, 3};
for (int n : nums) {
n = n * 2; // does NOT modify array
}
for (int n : nums) {
System.out.println(n);
}
Explanation
- Enhanced loop variable is a copy.
- Original array remains unchanged.
14. Enhanced for-each Loop vs Index Loop (Comparison)
int[] nums = {10, 20, 30};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
for (int n : nums) {
System.out.println(n);
}
Explanation
- for-each is simpler.
- Index loop needed when index manipulation is required.
15. Enhanced for-each Loop with Filtering Logic
int[] nums = {5, -2, 8, -1};
for (int n : nums) {
if (n < 0) continue;
System.out.println(n);
}
Explanation
- Skips negative numbers.
- Clean filtering pattern.
16. Enhanced for-each Loop with Boolean Flag
int[] nums = {3, 6, 9};
boolean found = false;
for (int n : nums) {
if (n == 6) {
found = true;
break;
}
}
System.out.println(found);
Explanation
- Common search pattern.
- break exits early.
17. Enhanced for-each Loop with Enum
enum Day { MON, TUE, WED }
for (Day d : Day.values()) {
System.out.println(d);
}
Explanation
- Iterates over enum constants.
- Very common interview question.
18. Enhanced for-each Loop with Var (Java 10+)
int[] nums = {1, 2, 3};
for (var n : nums) {
System.out.println(n);
}
Explanation
- var infers type automatically.
- Improves readability.
19. Enhanced for-each Loop with Lambda Comparison
Listlist = List.of(1, 2, 3); for (int n : list) { System.out.println(n); } list.forEach(n -> System.out.println(n));
Explanation
- Shows traditional vs lambda iteration.
- for-each is more readable for beginners.
20. Interview Summary Example (Enhanced for-each)
String[] langs = {"Java", "Python"};
for (String lang : langs) {
System.out.println(lang);
}
Explanation
- Best used when:
- No index needed
- Read-only traversal
- Very common interview example.
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.