What is foreach Java loop?


for loop is used to iterate any data in Java as in most of the languages. To make the iteration of elements easier, the general for loop can be replaced with a new loop known as foreach Java loop in JDK 1.5. But this new foreach Java loop should be used only in arrays and collections classes only.
The foreach Java loop with arrays is shown in Arrays Enhanced for loop and foreach with collections classes is shown in the following example with ArrayList.
import java.util.*;
public class ForEachDemo
{
  public static void main(String args[])
  {
    ArrayList al = new ArrayList();
    al.add("Banana");
    al.add("Apple");
    al.add("Lemon");
    al.add("Straw Berry");

    System.out.print("\nGeneral for loop:  ");
    for(int i = 0; i < al.size(); i++)
    { 
      System.out.print(al.get(i) + ", ");
    }
    
    System.out.print("\n\nforeach for loop:  ");
    for(String str : al)
    { 
      System.out.print(str + ", ");
    }
  }
}

foreach Java

Let us see how the new foreach loop works.

for(String str : al)
{
System.out.print(str + ", ");
}

In the new loop, the initialization, test condition and incrementing is done implicitly. In the first iteration, the first element of ArrayList al is copied into string str. Now str is printed. In the next iteration, the second element is copied and is printed and like this goes for all the elements.

Leave a Comment

Your email address will not be published.