For-Each Loop in Java [With Coding Examples]

Every programming language uses loops to execute the same block of code iteratively. Java has different types of loop statements, viz. for loop, while loop, do-while loop. Another kind of loop introduced in the Java 5.0 version is the for-each loop, also called enhanced for loop.

It uses the same keyword ‘for’ as in for loop to iterate in collecting items, such as an array. In a for-each loop, there is no need to initialize the loop counter variable. Instead, a variable is declared along with the array name. To get more understanding of its usage, check the syntax of the for-each loop in Java.

Syntax of For-Each Loop in Java

for(data_type variable_name : array_name) {

           Statements;

}

Here, data_type is the data type of the variable declared with the name variable_name. array_name is the array in which the variable will iterate to execute the statements inside the loop block.

How Does For-Each Loop Work?

For-each loop in Java works like any other loop. The loop traverses for each element of the array till last. The value of the array element is stored in the variable declared with the loop, and execution of the statement occurs for each iteration.

Read: Java Developer Salary in India

Examples of the For-Each Loop in Java

Example 1: Consider the below example that adds the elements of the array and prints the result.

Class Example1 {

Public static void main(String args[]) {

int count[] = {1, 3, 5, 7, 9};

int sum=0;

for(int var : count) {

                            sum = sum + var;

}

System.out.println(“Sum of the array elements “ + sum);

}

}

Output: Sum of the array elements 25

Explanation: In the above program, for each iteration, the array element gets assigned to var and gets added to the variable called sum.

For the first iteration, var = 1, and the sum, which was initially 0, gets added to var, i.e., 1. Therefore, the sum becomes 1 after the first iteration.

For second iteration, var = 3 and sum = sum + var = 1 + 3 = 4

For the third iteration, var = 5 and sum = 4 + 5 = 9.

In this way, the sum gets updated after each iteration and gives the sum of all elements of the array.

Example 2: The below code snippet prints the elements of the string collection.

Class Example2 {

Public static void main(String args[]) {

String firstName[] = {“Peter”, “John”, “Mary”};

for(int name : firstName) {

                            System.out.println(“Name is “ + name);

}

}

}

Output:

Peter

John

Mary

Explanation: In this example, the variable declared as the name takes the value of firstName from the collection of strings and prints it.

How is the For-Each Loop Different from For Loop?

If we write the above code using for loop, it will be as below:

Class Example1 {

Public static void main(String args[]) {

int count[] = {1, 3, 5, 7, 9};

int sum=0;

for(int var=0; var < count.length; var++) {

                            sum = sum + var;

}

System.out.println(“Sum of the array elements “ + sum);

}

}

By comparing the code of for loop and for-each loop, it is clear that it is easy to write the code using the for-each loop. There is no need to initialize the counter variable and increment or decrement in the for-each loop as the loop automatically moves to the next element in the array.

Advantages of For-Each Loop in Java

  • The use of the for-each loop is easy and makes the code readable.
  • The for-each loop does not use the index of the array to traverse in the loop.
  • This loop reduces the chance of programming error.
  • The for-each loop works faster than the for loop.

Disadvantages of For-Each Loop in Java

There are certain disadvantages of using the for-each loop as discussed below:

  • It is impossible to traverse in the reverse order in the for-each loop as is done in for loop or while by decrementing the counter variable.
  • There is no way to skip the array element while using the for-each loop.
  • It is impossible to refer to the odd or even elements in the array as possible in for loop where the counter variable can be incremented or decremented by two or even more.

Checkout: Java Project Ideas & Topics

Conclusion

The use of the for-each loop in Java makes the code more readable and easy to understand. Therefore, it is recommended to use the for-each loop instead of for loop. However, it has the disadvantage that elements cannot be traversed in reverse order or cannot skip the array elements. But the use of ‘break’ and ‘continue’ can let the coders modify the code as per the need. Java is a popular language for software development. You can learn software development from upGrad by applying for Masters in Computer Science.

If you’re interested to learn more about PHP, Full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Land on Your Dream Job

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN FULL STACK
ENROLL TODAY

Leave a comment

Your email address will not be published. Required fields are marked *

×