what is enhanced for loop in Java?

Java Programming Java8Java Technologies Object Oriented Programming

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse a collection of elements including arrays.


Following is the syntax of enhanced for loop −

for(declaration : expression) {
   // Statements
  • Declaration − The newly declared block variable is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

  • Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.


Live Demo

public class Test {

   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};

      for(int x : numbers ) {
         System.out.print( x );
      String [] names = {"James", "Larry", "Tom", "Lacy"};

      for( String name : names ) {
         System.out.print( name );


This will produce the following result −

10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,
Published on 22-Jan-2018 08:18:41