Java Enhanced for loop Example Program

Java Enhanced for loop feature is introduced java 1.5 version.
Java Enhanced for loop is most useful to retrive the elements from the Arrays&Collections.
here important point is enhanced for loop is applicable only for Arrays&Collections.








structure of java enhanced for loop

for(datatype variablename:arrays/collections){
  //statements
}

java enhanced for loop example program to retrieve array
package com.java2study;

public class EnhancedForLoopDemo {
 public static void main(String[] args) {
  int number_array[] = { 1, 2, 3, 4, 5 };

  for (int n : number_array) {
   System.out.println(n);
  }
 }
}

output


java enhanced for loop example program to retrive collections
import java.util.*;

public class EnhancedForLoopDemo1 {
 public static void main(String[] args) {
  List list = new ArrayList();

  list.add(1);
  list.add(2);
  list.add(3);
  list.add(4);
  list.add(5);

  for (int i : list) {

   System.out.println(i);

  }
 }
}