Since Java 1.5, the for-each loop or enhanced for loop is a concise way to iterate over the elements of an array and a Collection. Simply put, the for-each loop is a short form of a for-loop without using the index counter variable.
The absence of the counter variable makes the code more readable and less error-prone. It removes the possibility of the well-known ArrayIndexOutOfBoundsException that is often seen in traditional for-loop.
1. Syntax
The for-each loop does not use the index variable. It uses a variable of the base type of the Collection or the array we will iterate, followed by a colon and finally the array/collection itself.
In the following code, the array contains the elements of type T. The item is the variable of type T, and in each iteration, the item refers to the current item in the array.
for(T item : array) {
...
}
The same syntax is used for primitives types, wrapper types and all other types of classes.
2. Iterating Through an Array
The following Java program iterates and prints all elements of an integer type array numArray.
int[] numArray = {10, 20, 30, 40};
for(int item : numArray) {
System.out.println(item);
}
The program iterates the array in four iterations.
- In first iteration, the item value is 10.
- In second iteration, the item value is 20.
- In third iteration, the item value is 30.
- In fourth and final iteration, the item value is 40.
The program output:
10
20
30
40
2. Iterating Through a List
The iteration logic remains the same for collection types also. We only need to pass the collection variable in place of the array.
List<String> list = List.of("A", "B", "C");
for(String item : list) {
System.out.println(item);
}
The program output:
A
B
C
4. Using forEach() Method
Since Java 8, the forEach() method is another way to iterate over all elements of an array of a collection, very similar to for-each loop. The forEach() method accepts a Consumer action that it applies to each element of the collection or array.
For example, we can rewrite the previous example of iterating the list as follows. The System.out::println is a method reference and of type the Consumer action. The program output is the same.
List<String> list = List.of("A", "B", "C");
list.forEach(System.out::println);
Drop me your questions related to for-each loop control flow statements in Java.
Happy Learning !!
Comments