For-Each Loop in Java [With Coding Examples]
Updated on Jul 03, 2023 | 8 min read | 7.6k views
Share:
For working professionals
For fresh graduates
More
Updated on Jul 03, 2023 | 8 min read | 7.6k views
Share:
Table of Contents
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.
Check out our free courses to get an edge over the competition
The for each loop in Java is also called the enhanced for loop. It has been in operation since JS2E 5.0. The for-each loop ensures that you have an alternative approach toward traversing a collection or array in Java. The name for-each loop stems from its ability to traverse elements one after the other.
The for-each loop is crucial for eliminating bugs and making code more readable. But unfortunately, you cannot skip elements or traverse them in reverse order while using the for-each loop. Additionally, you cannot use the for-each loop for traversing only the odd or even elements.
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.
Check out upGrad’s Advanced Certification in Blockchain
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.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Some common characteristics of the for-each loop in Java are as follows:
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);
}
}
Check out upGrad’s Advanced Certification in DevOps
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.
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.
Suppose you want the following output:
a
e
i
o
u
Now, let us glance at the code using the for loop to get this outcome:
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]);
}
}
}
Now, let us look at a Java for-each loop example for the same outcome:
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);
}
}
}
By looking carefully at the two codes, you will understand that the for-each loop makes it easy to read and write. That’s why the for-each loop gets preferred over the for loop.
There are certain disadvantages of using the for-each loop as discussed below:
Checkout: Java Project Ideas & Topics
A few limitations of the for-each loop in Java are as follows:
Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
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 Executive PG Program 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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources