Enhanced for Loop (for-each)
The enhanced for loop (also called for-each loop) is used to iterate through arrays or collections in a simpler and cleaner way — without using an index.
Key Points :
- Used to traverse arrays or collections easily.
- No need to manage index or loop counters.
- Automatically picks each element one by one.
- Read-only loop — you can access, but not change the original array values directly.
- Best for reading values, not for updating them.
Syntax:
for (datatype var : array) {
// code using var
}
- for (datatype var : array) means take each element from the array one by one.
- var holds the current element in each iteration.
- The loop runs automatically for each value, without using index or counters.
Example:
class ShikshaSanchar {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println("Number: " + num);
}
}
}
Output:
Number: 10
Number: 20
Number: 30
Number: 40
Number: 50
Explanation :
- int[] numbers is an array of integers.
- The enhanced for loop goes through each number in the array.
- On each iteration, num holds the current value from the array.
- The loop prints each number one by one.
- No need to write numbers[i] or manage i++.
Flowchart : for-each Loop in Java
This diagram visually shows how a for-each loop works — where each element of the array/collection is picked automatically.
- Start
- The program begins execution.
- Control moves to array declaration.
- Declare Array
-
int[] numbers = {10, 20, 30, 40, 50}; - An array of integers is declared.
- This step sets up the values the loop will iterate over.
-
- Loop Begins
-
for (int num : numbers) - The enhanced for loop starts.
- It automatically picks the first element (10) from the array.
-
- Print Statement
-
System.out.println("Number: " + num); - Prints the current value of num.
- First time: prints Number: 10, then Number: 20, and so on...
-
- Next Element?
- Checks: Are there more elements left in the array?
- If Yes Loop goes back to pick the next element → Step 3.
- If No All elements are done → move to End.
- End
- Loop is finished.
- The program ends after printing all values from the array.
When to Use:
- When you just want to read or display elements.
- When you don’t need the index of elements.
- Perfect for arrays, ArrayList, HashSet, etc.
Limitations:
- You can’t modify array elements directly.
- You can’t access index inside the loop.
Summary:
- Simplifies array/collection traversal.
- No index or counter is needed.
- Easy to read and write.
- Best for read-only tasks.
- Can’t access index or modify elements directly.