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
Everything You Need to Know About the For-Each Loop in Java
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.
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.
Check out upGrad’s Advanced Certification in Blockchain
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
Explore Our Software Development Free Courses
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Features of the For-Each Loop
Some common characteristics of the for-each loop in Java are as follows:
- The first keyword in the for-each loop is “for,” similar to a regular for loop.
- While using the for-each loop, you don’t declare and initialize a loop counter variable. Instead, you will have to declare a variable similar to the base type of the array. It is then succeeded by a colon and the array name.
- In the loop body, you are not required to use the indexed array element. Instead, you will be able to leverage the loop variable you made.
- The for-each loop in Java is used for iterating over an array or a Collections class like an ArrayList.
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); } }
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.
Explore our Popular Software Engineering Courses
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.
Understanding the Difference Between For Loop and For-Each Loop from the Same Example
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.
In-Demand Software Development Skills
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.
Read our Popular Articles related to Software Development
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
Limitations of the For-Each Loop
A few limitations of the for-each loop in Java are as follows:
- They are not useful for modifying the array.
- The for-each loop cannot be used for obtaining the array index because they don’t keep track of the index.
- They are useful for iterating forward over the array only in single steps.
- The for-each loop cannot be used for processing two decision-making statements at once.
- It will show some performance overhead even over a simple iteration.
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.
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 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.
What are loops in programming?
A loop is a way to repeat one or more lines of code a specified number of times. This is extremely useful when you have instructions that you want to repeat over and over. Without loops, you would have to write every step of the instructions every time that you run the program. Breaking a program down into smaller pieces allows you to focus on each piece separately. The code inside the loop will be executed a number of times equal to the number of times the loop iterates. The loop will execute line by line and once the loop iterates for the last time, the program will continue with the next statement after the loop.
What are the different types of loops in Java?
There are several types of loops in Java. The first one and probably, the most frequently used loop is the for loop. In case of a for loop, you define a structure such as for (int i = 0; i <= 20; i++) {}. Here, the statements inside the curly braces will be executed 21 times. This means that as long as the value of i starting from 0 is less than or equal to 20, the statements will get executed provided it does not encounter a break statement. The next loop is the while loop. The while loop will continue to execute until it satisfies the condition mentioned or if it encounters a break statement in which case it will come out of the loop. Another version of the while loop is the do while loop. The difference is that the do while loop executes at least once because the condition is specified at the end of the curly braces. Yet another type of loop is the foreach loop which is a simplified version of the for loop. This loop allows you to traverse an array and loop through each element of it.
What are the uses of loops in programming?
Loops are a fundamental programming construct that allow us to do repetitive tasks. The use of loops is probably the most common in a standard computer application. Loops are used for tasks such as reading and writing files or arrays, searching or sorting through items or data, and many other common tasks.