For Each Loop in Java

In this tutorial we are going to learn about for each loop in Java which is an advanced form of for loop with the help of some examples.


In Java programming, when we are working with an array or multiple arrays we use the advanced form of for loop which is known as a for-each loop. We call it a for each loop because this loop repeats itself by going through each element that is present inside an array or a collection.

If you’re not introduced with the concept of loops in Java, then you can go through the for loop tutorial to understand for-each loop in detail.

Recommended Books



Syntax of For-Each Loop

The syntax of for-each loop is pretty different from the for loop syntax, the for-each loop has:

for(type_of_data option : collection/arrays) {

}

Understanding For loop and For-each Loop

In order to understand why for-each loop is preferred over for loop, we need to see a working example that iterates through an array. Let’s find out how we can iterate through the strings in an array using the for loop.

Example:

public class for_each {
  public static void main(String args[]) {
    String[] arr = {
      "I",
      "Love",
      "Programming"
    };
    for (String words: arr) {
      System.out.println(words);
    }
  }
}

Output

I
Love
Programming

Above you can see that the output of the program is similar to what we have learnt in for loops but if you carefully notice, then the for each loop is easier to understand and the code is more short and readable.