Tuesday, January 10, 2012

JAVA Programming : For Each Loop

JAVA For Each Loop


For each loop or Enhance For loop is a extended version of basic for loop which was introduced in Java 5. For each loop is designed to make iteration over arrays and collections much easier. For each loop also makes the code more readable. In this post we will learn about basics of For each loop using  Arrays. We will discuses more about For Each loop when we learn about Collections and Iterator.

Syntax of For Each Loop:-

        for (type var : arr) {  
        //body-of-loop  
    }

Example of For Each Loop:- This is a very simple example in which we will traverse an array using For Each loop and print all the elements of the array.


public class ForLoop {
  public static void main(String[] args) {
    char[] charArr = {'a','b','c','d','e'};    
    for (char c : charArr) {
      System.out.println(c);
    }
  }
}



To understand the difference between Basic For loop and For Each Loop, here is the same program using For Loop.


public class ForLoop {
  public static void main(String[] args) {
    char[] charArr = {'a','b','c','d','e'};    
    for (int i = 0; i < charArr.length; i++) {
      System.out.println(charArr[i]);
    }
  }
}



Advantages of For Each Loop:-
  • Less number of variables are used
  • Less chance of errors
  • Improve Readability 
Limitation of For Each Loop:- 
  • Cannot traverse multiple collection at once.
  • Iterates only forward by single steps.