Home > Java > javaTutorial > For-Each loop in Java

For-Each loop in Java

WBOY
Release: 2024-08-30 15:25:22
Original
1203 people have browsed it

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
Copy after login

The explanation for each of the terms used above is as follows:

  1. ‘type’ indicates the data type of the objects of the
  2. ‘iter_var’ indicates the iteration variable name, which stores each value of the Collection as we iterate through the loop.
  3. ‘Collection’ specifies the Collection or array through which we want to iterate.
  4. ‘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.

For-Each loop in Java

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:

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));
}
}
Copy after login

Output:

For-Each loop in Java

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));
}
}
Copy after login

Output:

For-Each loop in Java

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 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);
}
}
Copy after login

Output:

For-Each loop in Java

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:

For loop with Different Conditions

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]+" ");
}
}
}
Copy after login

Output:

For-Each loop in Java

The output of for loop showing updation of the original array

Foreach loop with Different Conditions

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+" ");
}
}
}
Copy after login

Output:

For-Each loop in Java

The output of the for-each loop showing no updation of the original array

Things to Remember About For-Each loop in java

  1. For-Each loop in java is used to iterate through array/collection elements in a sequence.
  2. For-Each loop in java uses the iteration variable to iterate over a collection or array of elements.
  3. Modifying the iteration variable does not modify the original array/collection as it is read-only.
  4. The type in the for-each loop must match the type of the original array/collection elements.
  5. Foreach loop does not need the number of iterations to be specified as it iterates over all elements of the collection.
  6. It is possible to stop the for-each loop using a break statement.

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!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template