Enhanced for loop also called advanced for loop or foreach loop is used to iterate over an array or a collection of elements such as list or set.
When a collection is iterated using advanced for loop, then in every iteration, the current collection element is assigned to a variable which should of the same data type as the collection.
This will be clear from its syntax below.
Enhanced for loop was introduced in java 1.5 and is also called a for-each loop probably because it contains a collection element in each iteration.

In these post, the terms enhanced for loop, advanced for loop and for-each loop will be used interchangeably but they mean the same.
Syntax of enhanced for loop
Enhanced for loop has the below syntax.

for(<data type of collection> <variable> : <collection>) {
// loop body
}

Variable is a user defined name which holds a value. In every iteration, the variable contains a collection’s element.
Thus, in first iteration, variable will have the first element, in second iteration, it will have second element and so on.
Remember that the data type of the variable should be the same as the collection’s data type.

If the collection is of some class type, then the variable’s data type should be of same type or its super-type.
Example, if the collection is a list of Cat, then variable can be of types Cat or Animal where Animal is the super class of Cat.
If the type of variable and collection are not compatible, then compiler will raise an error, thus saving the program to break at run time.
Enhanced for loop example
An example of enhanced for loop is given below.
It creates a String array and then iterates over it using the loop.

public class AdvancedForLoopDemo {
   public static void main(String[] args) {
      // initialize a String array
      String[] array = {"java", "javascript", "python"};
      // iterate over array
      for(String language: array) {
         System.out.println("Current array element is " + language);
      }
   }
}

Output of this program is

Current array element is java
Current array element is javascript
Current array element is python

Enhanced for loop vs for loop
When iterating over a collection, enhanced for loop or for-each loop should be preferred over traditional for loop since it offers some advantages listed below.

  • It has a shorter syntax as compared to the traditional for loop.
  • It offers type checking at compile time thus reducing chances of run time errors.
  • Current array or collection item is initialized in loop statement only, thus you do not need a separate statement for that.

Below example shows both loops iterating over an array of a Student class.

class Student {
	
   /**
    * Fields
    */
   String id;
   String name;

   /**
    * Constructor
    * @param id
    * @param name
    */
   public Student(String id, String name) {
      this.id = id;
      this.name = name;
   }

  /**
    * Getter and setter methods
    */
   public String getId() {
      return id;
   }

   public void setId(String id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

public class AdvancedForLoopDemo {

   public static void main(String[] args) {
      // create student objects
      Student studentOne = new Student("1", "A Z");
      Student studentTwo = new Student("2", "B Y");
      Student studentThree = new Student("3", "C X");
      // initialize student array
      Student[] students = { studentOne, studentTwo, studentThree };
	
      // iterate with for loop
      for (int i = 0; i < students.length; i++) {
        Student student = students[i];
        System.out.println("Student id: " + student.getId());
        System.out.println("Student name: " + student.getName());
      }
		
      // iterate with enhanced for loop
      for (Student student : students) {
        System.out.println("Student id: " + student.getId());
        System.out.println("Student name: " + student.getName());
      }
   }
}

Clearly, enhanced for loop has a shorter and cleaner syntax.

If during iteration, you need an index of current element, then with enhanced for loop, you need to initialize a separate variable outside the loop.
This index should be incremented in each iteration while with traditional for loop, it is initialized in the loop statement only.
This is one advantage that you get with primitive for loop.

Leave a Reply