Introduction to For-Each loop in Java
For each loop has been introduced in Java starting from JDK 5. It aims to iterate sequentially through all the elements of a Collection or array. It is also there in other languages like C#, where it uses the keyword for-each. However, Java uses the keyword ‘for’ only to implement for-each loop unlike C# but its syntax differs from the conventional for a loop. This for-each loop is also known as enhanced for loop in Java.
Syntax:
for(type iter_var : Collection) statement_block
The explanation for each of the terms used above is as follows:
- ‘type’ indicates the data type of the objects of the
- ‘iter_var’ indicates the iteration variable name which stores each value of the Collection as we iterate through the loop.
- ‘Collection’ specifies the Collection or array through which we want to iterate.
- ‘statement-block’ is the set of statements that we want to execute for each iteration of the loop.
It is essential to note that the for-each loop accesses the collection/array elements sequentially where it stores the value of each element in the iteration variable. Following is the flow diagram of the for-each loop.
As you have noticed, there are certain subtle differences between for loop and for-each loop. For loop requires the number of iterations to be specified beforehand. However, this is not the case with the for-each loop, as the loop iterates from the first element to the last element of the Collection/array and does not need the number of iterations to be specified.
An important point to be kept in mind is that the type specified in the for-each loop must match the type of the elements in the collection because otherwise there will be compatibility issues.
Examples of For-Each Loop in Java
Following are the different examples:
1. For loop
Let us find the average age of a group of people using for loop:
4.8 (8,018 ratings)
View Course
Code:
public class Main
{
public static void main(String[] args) {
int ages[] = {15, 18, 16, 17, 14, 12, 13, 20, 22, 25};
int sum = 0;
System.out.print("Ages of the group are : "); for (int i = 0; i < 10 ; i++)
{
System.out.print(ages[i]+" "); sum += ages[i];
}
System.out.println("\n Average age of the group = " + (sum/10));
}
}
Output:
2. For-Each Loop
To find the average age of a group of people using a for-each loop:
Code:
public class Main
{
public static void main(String[] args) {
int ages[] = {15, 18, 16, 17, 14, 12, 13, 20, 22, 25};
int sum = 0;
System.out.print("Ages of the group are : "); for (int x : ages)
{
System.out.print(x+" "); sum += x;
}
System.out.println("\n Average age of the group = " + (sum/10));
}
}
Output:
The output is the same using both the loops as seen from the above figures.
Foreach loop using Break Statement
It is possible to reduce the number of iterations of the for-each loop using a break statement. For eg, if we want to find the sum of only the first 5 elements, we can use the break statement as follows:
Code:
public class Main
{
public static void main(String[] args) {
int ages[] = {15, 18, 16, 17, 14, 12, 13, 20, 22, 25};
int ctr = 0, sum = 0;
System.out.print("Ages of the group are : "); for (int x : ages)
{
System.out.print(x+" ");
}
for (int x : ages)
{
if (ctr == 5) break; sum += x;
ctr += 1;
}
System.out.println("\nSum of age of first 5 people of the group = " + sum);
}
}
Output:
In the for-each loop mentioned above, x is the iteration variable that stores one element of the array per iteration which changes in the next iteration. In the first iteration, x stores the first element of the array and the last element of the array in the last iteration. Unlike for loop, where we access the elements of the array using the index, for each loop uses iteration variable to access the elements.
Care needs to be taken in using for each loop as the iteration variable stores the value of the array element temporarily as it is “read-only” and changing its value does not modify the original array. This contradicts for loop where changing an element modifies the original array.
Let’s consider an example where we add 5 to each element of the array. We can spot the difference in the output in the following example code:
For loop with Different Conditions
The for loop with different conditions are explain below:
Code:
public class Main
{
public static void main(String[] args) {
int ages[] = {15, 18, 16, 17, 14, 12, 13, 20, 22, 25};
System.out.print("Elements of the array are : "); for (int i = 0; i < 10; i++)
{
System.out.print(ages[i]+" "); ages[i]+= 5;
}
System.out.print("\nNew elements of the array are : "); for (int i = 0; i < 10; i++)
{
System.out.print(ages[i]+" ");
}
}
}
Output:
The output of for loop showing updation of the original array
Foreach loop with Different Conditions
The for loop with different conditions are explain below:
Code:
public class Main
{
public static void main(String[] args) {
int ages[] = {15, 18, 16, 17, 14, 12, 13, 20, 22, 25};
System.out.print("Elements of the array are : "); for (int x : ages)
{
System.out.print(x+" "); x += 5;
}
System.out.print("\nNew elements of the array are : "); for (int x : ages)
{
System.out.print(x+" ");
}
}
}
Output:
The output of the for-each loop showing no updation of the original array
Things to Remember About For-Each loop in java
- For-Each loop in java is used to iterate through array/collection elements in a sequence.
- For-Each loop in java uses the iteration variable to iterate over a collection or array of elements.
- Modifying the iteration variable does not modify the original array/collection as it is read-only.
- The type in the for-each loop must match the type of the original array/collection elements.
- Foreach loop does not need the number of iterations to be specified as it iterates over all elements of the collection.
- It is possible to stop the for-each loop using a break statement.
Recommended Articles
This is a guide to the For-Each loop in java. Here we discuss the For-Each loop in java with its code implementation in different ways that is with break statement and with the various conditions. You may also look at the following articles to learn more –