Java for-each Loop
In this tutorial, we will learn about the Java for-each loop and its difference from the classical for loop with the help of examples.
In Java, we use the for-each loop to iterate through elements of arrays and collections.
for-each Loop Syntax
The syntax of the Java for-each loop can be given as follows:
for(dataType item : collection) {
...
}
Here,
collection- is a collection or an arrayitem- each item of collection/array is assigned to this variabledataType- is the data type of the collection/array
Example: Display Array Elements
In the following example, we will use the for-each loop through an array of numbers.
public class Main {
public static void main(String[] args) {
int[] numbArray = {27, 5, 9, 18, 55};
for(int numb : numbArray) {
System.out.println(numb);
}
}
}
Output
27
5
9
18
55
Here, we have used the for-each loop to go through each element of the numbArray and display it.
- 1st iteration,
itemwill be 27. - 2nd iteration,
itemwill be 5. - 3rd iteration,
itemwill be 9. - 4th iteration,
itemwill be 18. - 5th iteration,
itemwill be 55.
Example: Calculate the Sum of Array Elements
In the following example, we will calculate the sum of an array of elements.
public class Main {
public static void main(String[] args) {
int[] numbArray = {27, 5, 9, 18, 55};
int sum = 0;
for(int numb : numbArray) {
sum += numb;
}
System.out.println("Sum = " + sum);
}
}
Output
Sum = 114
The execution of the above program of the for-each loop can be given as follows:
| Iteration | Variables |
|---|---|
| 1st | numb = 27 sum = 0 + 27 |
| 2nd | numb = 5 sum = 27 + 5 |
| 3rd | numb = 9 sum = 32 + 9 |
| 4th | numb = 18 sum = 41 +18 |
| 5th | numb = 55 sum = 59 + 55 = 114 |
As we can see above, we have added each numbArray element to the sum variable in each iteration of the for-each loop.
Difference between for loop and for-each loop
Let us see how a classical Java for loop is different from a for-each loop.
To see the difference between the for-each loop and classical Java for loop, we will write the same program using the two different for loops.
Using for loop
public class Main {
public static void main(String[] args) {
String[] fruits = {"kiwi", "pineapple", "orange", "grapes"};
for(int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
}
Output
kiwi
pineapple
orange
grapes
Using for-each loop
public class Main {
public static void main(String[] args) {
String[] fruits = {"kiwi", "pineapple", "orange", "grapes"};
for(String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output
kiwi
pineapple
orange
grapes
As we can see above, the output of both programs is the same.
So the difference between fo-each, and for loops is that the for-each loop is easy to write and understand comparing to the classical for loop.
Note: The
for-eachloop is preferred over the classicalforloop when working with collections and arrays.
