How does the java "for each" loop works



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

Syntax

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.

Example

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 );
         System.out.print(",");
      }
      System.out.print("
");       String [] names = {"James", "Larry", "Tom", "Lacy"};       for( String name : names ) {          System.out.print( name );          System.out.print(",");       }    } }

Output

This will produce the following result −

10, 20, 30, 40, 50, James, Larry, Tom, Lacy,

Advertisements