For Each Loop In Java

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

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription