In this article, you will learn-
Java for-each Loop
In this tutorial, we will find out about the Java for-each loop and its distinction with for loop with the help of examples.
In Java, the for-each loop is used to iterate through elements of arrays and assortments (like ArrayList). It is otherwise called the upgraded for loop.
for-each Loop Syntax
The syntax of the Java for-each loop is:
for(dataType item : array) {
...
}
Here,
- array – an array or a collection
- item – each item of array/collection is assigned to this variable
- dataType – the data type of the array/collection
Example 1: Print Array Elements
// print array elements
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
// for each loop
for (int number: numbers) {
System.out.println(number);
}
}
}
Output
3
9
5
-5
Here, we have used the for-each loop to print every component of the array one by one.
- In the first iteration, the item will be 3.
- In the second iteration, the item will be 9.
- In the third iteration, the item will be 5.
- In the fourth iteration, the item will be -5.
Example 2: Sum of Array Elements
// Calculate the sum of all elements of an array
class Main {
public static void main(String[] args) {
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
// iterating through each element of the array
for (int number: numbers) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output
Sum = 19
In the above program, the execution of the for each loop looks as:
Iteration | Variables |
---|---|
1 | number = 3 sum = 0 + 3 = 3 |
2 | number = 4 sum = 3 + 4 = 7 |
3 | number = 5 sum = 7 + 5 = 12 |
4 | number = -5 sum = 12 + (-5) = 7 |
5 | number = 0 sum = 7 + 0 = 7 |
6 | number = 12 sum = 7 + 12 = 19 |
As should be obvious, we have included every component of the numbers array to the sum variable in every iteration of the loop.
for loop Vs for-each loop
Let’s see how a for-each loop is different from a regular Java for loop.
1. Using for loop
class Main {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// iterating through an array using a for loop
for (int i = 0; i < vowels.length; ++ i) {
System.out.println(vowels[i]);
}
}
}
Output
a
e
i
o
u
2. Using for-each Loop
class Main {
public static void main(String[] args) {
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
// iterating through an array using the for-each loop
for (char item: vowels) {
System.out.println(item);
}
}
}
Output
a
e
i
o
u
Here, the output of the two projects is the equivalent. Be that as it may, the for-each loop is simpler to compose and comprehend.
This is the reason the for-each loop is favored over the for loop when working with arrays and assortments.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.