![]() |
VOOZH | about |
The for-each loop in Java (introduced in Java 5) provides a simple, readable way to iterate over arrays and collections without using indexes.
Example: Iterating Over an Array
1 2 3 4 5
Explanation:
for (datatype variable : arrayOrCollection) {
// statements using variable
}
Parameters:
Use for-each loop when:
Avoid using for-each loop when:
Example 1: Finding Maximum in an Array using for-each Loop
132
Explanation:
Example 2: Iterating in a List using for-each loop
List of Integers: [3, 5, 7, 9] Maximum element: 9
Explanation: In the above example, we use the for-each loop to iterate the list of integer to find the largest or maximum value in the list. Here, we use the Integer.MIN_VALUE which is the minimum value of integer and compare it the element of list and check if the element is greater than the max then update the max value.
While the for-each loop is convenient, there are some important limitations to consider:
for (int num : marks) {
num = num * 2; // Does not modify array
}
Explanation:The loop variable holds a copy of the value, not the actual array element.
for (int num : numbers) {
if (num == target) {
// do not know the index of 'num' here
return ???; // Index is unavailable in for-each loop
}
}
Explanation: The for-each loop does not provide access to the index of the current element. If we need the index for any reason (e.g., in a search operation), a traditional loop would be more appropriate.
// Traditional reverse iteration
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println(numbers[i]); // Reverse iteration not possible with for-each
}
Explanation: The for-each loop allows only forward iteration. Reverse iteration requires a traditional for loop with an index.
Note:
- The for-each loop works with arrays and all classes that implement Iterable
- It improves code readability and reduces boilerplate
- Internally, it uses an iterator for collections
- Best suited for simple traversal and read-only operations