Tutorials

Java Loop Control


Enhanced for loop


Enhanced for loop or for each loop was introduced with release of Java SE 5.0
It is very helpful when trying to iterate over element of array or Collection. 
 

Advantage of enhanced for loop

  • It increases the readability of the code.
  • You don’t need to take overhead of initializing the variable, checking condition and incrementing the variable as is done in for loop.

Disadvantage of enhanced for loop

  • It doesn’t allow accessing the index of the element when iterating over loop.
  • It doesn’t allow modifying (remove) the item of array/Collection.
Syntax:
for(dataType var : array/collection){
  //code to execute
}

 
Example 1: for each loop with Array
 
public class simpleExample {

    public static void main(String[] args) {
      String[] strArray = {"xyz","abc","pqr","lmn"};

       for(String s : strArray){
         System.out.println(s);
       }

    }

}

OUTPUT:
xyz
abc
pqr
lmn
 
Example 2: for each loop with Collection
 
import java.util.ArrayList;

public class simpleExample {

    public static void main(String[] args) {

      ArrayList al = new ArrayList();
      al.add("xyz");
      al.add("abc");
      al.add("pqr");
      al.add("lmn");

        for(String s : al){
          System.out.println(s);
        }
    }
}

OUTPUT:
xyz
abc
pqr
lmn
 
Difference between for loop and enhanced or for each loop.
 


Please Share this page
Views : 122
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!