In this article, you will learn about the for-each loop and how to create for-each loop in Java programming.
Apart from the standard for loop, Java provides you another form of for loop to work with arrays or collection, known as the enhanced for loop.
To learn more about standard for loop in Java visit here.
Java for-each Loop
The Java for-each loop or enhanced for loop provides an alternative approach to traverse through the items of arrays or collection.
It is known as the for-each loop because it traverses through each element (sequentially )of array/collection.
The purpose of for-each loop is to do something for every element rather than doing something n times.
The for-each loop starts with the keyword for like a normal for loop as shown below:
Syntax
for (data_type item : collection) {
// Do something to item
}
In the above syntax,
- collection : refers collection (ArrayList) or array variable which you want to traverse through.
- item : refers to a single item from the collection.
How for-each loop works?
When the Control falls into the for-each loop, for each iteration:
- traverse through each item in the given collection or array.
- stores each item in a variable.
- executes the body of the for-each loop
Traversing the array using for Loop
Here’s an example to iterate through elements of an array using the standard for loop:
Example
public class ForLoop { public static void main(String[] args) { //declaring an array int[] numbers = {10, 20, 30, 40}; //traversing the array with for loop for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } }
Traversing the array using for-each Loop
You can perform the same task using for-each loop as follows:
Example
public class ForEachLoop { public static void main(String[] args) { //declaring an array int[] numbers = {10, 20, 30, 40}; //traversing the array with for-each loop for (int number : numbers) { System.out.println(i); } } }
Output
The output of both programs will be the same :
10 20 30 40
Example: for-each Loop
The below program will print the sum of elements of an array.
public class ForEachLoop { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40}; int sum = 0; for (int number : numbers) { sum = sum + number; } System.out.println("Sum = " + sum); } }
Output
Sum = 100
Example explained
In the above example, during each iteration, the for-each loop:
- traverse through each element in the numbers variable
- stores it in the number variable
- execute the body, i.e. add a number to sum