Enhanced For Loop Java List Example

 
The enhanced for loop repeatedly executes a block of statements by iterating over a array or collection 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;
 
/**
 * Program to use enhanced for loop example in java.
 * @author javawithease
 */
public class EnhancedForLoopExample {	
	static void enhancedForLoopTest(List<String> arrayList){
		//Enhanced For loop test
		for (String name : arrayList) {
			System.out.println(name);
		}
	}	
 
	public static void main(String args[]){ 
		//Create ArrayList object. 
		List<String> arrayList = new ArrayList<String>();   
		//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

Download this example.