Java Enhanced For Loop

The enhanced for loop repeatedly executes a block of statements by iterating over an array or collection of elements.

Syntax

for(declaration : expression) {
   //Block of Statements
}

 

Where:

  • declaration: is used to declare the new variable.
  • expression: is the array or collection object to be iterated.

Program to use enhanced for loop example in Java.

import java.util.ArrayList;
import java.util.List;

public class EnhancedForLoopExample {	
	static void enhancedForLoopTest(List arrayList){
		//Enhanced For loop test
		for (String name : arrayList) {
			System.out.println(name);
		}
	}	
	
	public static void main(String args[]){ 
		//Create ArrayList object. 
		List arrayList = new ArrayList();   
		//Add objects to the HashSet. 
		arrayList.add("Mahesh"); 
		arrayList.add("Vishal"); 
		arrayList.add("Anil"); 
		arrayList.add("Binod"); 
		arrayList.add("Pardeep"); 
                arrayList.add("Neeraj"); 
		//method call 
		enhancedForLoopTest(arrayList); 
	}
}

Output

Mahesh
Vishal
Anil
Binod
Pardeep
Neeraj