The for-each loop in Java is a simplified version of the traditional for
loop, used to iterate over collections or arrays. It eliminates the need for using an index and directly accesses each element in the collection or array.
Syntax of the for-each loop:
for (datatype variable : array_or_collection) {
// Code to be executed for each element
}
datatype
: The type of the elements in the array or collection (e.g.,int
,String
,Object
).variable
: A temporary variable that holds each element of the array or collection as the loop iterates.array_or_collection
: The array or collection that you want to iterate over (e.g., an array, aList
, aSet
).
Example 1: Iterating over an Array
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Using for-each loop to iterate over the array
for (int number : numbers) {
System.out.println(number);
}
}
}
Output:
1
2
3
4
5
Example 2: Iterating over a List
import java.util.*;
public class ForEachListExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Using for-each loop to iterate over the List
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output:
Apple
Banana
Cherry
Advantages of the for-each Loop:
- Simpler syntax: You don’t need to manage the loop index or the length of the array/collection.
- Readability: The loop is easier to read and write, especially when you’re only interested in the elements.
- Safety: It reduces the risk of errors like
ArrayIndexOutOfBoundsException
orConcurrentModificationException
(in certain situations).
Limitations of the for-each Loop:
- No access to index: You can’t access the index of elements while iterating.
- Read-only iteration: You can’t modify the elements of the array or collection during the iteration, as it’s designed for read-only operations.
In general, the for-each loop is a great tool when you just need to access the elements of a collection or array and don’t need the index. For more complex operations involving indices or modifications, a traditional for
loop is more suitable.