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 a for-each loop, unlike C#, but its syntax differs from the conventional for a loop. This for-each loop is also known as the enhanced for loop in Java.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
for(type iter_var : Collection) statement_block
The explanation for each of the terms used above is as follows:
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.
Following are the different examples:
Let us find the average age of a group of people using for 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 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:
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.
It is possible to reduce the number of iterations of the for-each loop using a break statement. For e.g., 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 last iteration element. Unlike for loop, we access the array elements using the index, for each loop uses an iteration variable to access the elements.
Care needs to be taken into 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:
The for loop with different conditions are explained 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
The for loop with different conditions are explained 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
The above is the detailed content of For-Each loop in Java. For more information, please follow other related articles on the PHP Chinese website!