For Each Loop In Java
Enhanced For Each Loop In Java
Like the for loop, while loop, and do-while loop, Java5 introduced the for-each technique as another array traversal method. For each loop in java performs better when we traverse to the end of the array.
Key Features of Enhanced Loop
- Like a standard for-loop, it begins with the word for.
- Instead of defining and initializing a loop counter variable, you define a variable whose type is the same as the array’s base type, followed by a colon and the array name.
- Instead of using an element from an indexed array, you can use the loop variable you created in the body of the loop.
- It is frequently used to iterate through an array or a Collections class (like ArrayList).
Syntax :
for (type var : array)
{
// statements using var;
}
Is Equivalent To:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
// Statement using var;
}
Example Code of For Each Loop in Java :
Run
public class Main {
public static void main(String[] args) {
// initialize loop variable i to 1
for (int i = 1; i <= 10; i++) {
// print i to the console
System.out.println(i);
}
}
}
Output
1 2 3 4 5 6 7 8 9 10
Explanation :
In this example, we define a class Main with a main method, which is the entry point for a Java application. Inside the main method, we declare and initialize the loop variable i to 1. We then use a for loop to iterate over the numbers from 1 to 10. The loop condition is i <= 10, which means that the loop will continue as long as i is
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Login/Signup to comment