For-each construct

One of the construct introduced since Java 1.5 is for-each loop. "for-each" loop is an enhanced version of a Java other looping constructs "for" and "while".

Just consider below example of code to fetch objects from ArrayList

public void print(List<Employee> list) {
for (Iterator<Employee> i = list.iterator(); list.hasNext(); )
{
System.out.println(list.next().getEmployeeNo());
}
}

"list" reference variable used in three places. So, there is a chance for the manual error. And if we want to print Employee name as well, one will just copy and paste the code as below.

public void print(List<Employee> list) {
for (Iterator<Employee> i = list.iterator(); list.hasNext(); )
{
System.out.println(list.next().getEmployeeNo());
System.out.println(list.next().getEmployeeName());
}
}

Adding the second line to print Employee name will break our program. As list.next() will return the next Employee object in the list. i.e; first employee number and second employee name will get displayed

For-each Syntax

for(<<variable definition>>:<<collection>>)
{
//Code
}

The above code can be simplified with for each construct as below

public void print(List<Employee> list) {
for (Employee emp:list)
{
System.out.println(emp.getEmployeeNo());
System.out.println(emp.getEmployeeName());
}

Colon (:) refers to in here. So, when we read it, for each Employee object in the collection list, execute the below code. We don't even have to type cast our object as for-each construct will take care of that behind the scenes. We can apply for-each construct to array of elements as well.

 for(String str:array)
{
}

Employee.java

/**
* This class demonstrates the for-each construct.
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 31 August 2012
*/

import java.util.ArrayList;

public class Employee
{
int id;
String name;

public Employee(int id, String name)
{
this.id = id;
this.name = name;
}

public String toString()
{
return "Employee[id="+id+", name="+name+"]";
}

public static void main(String args[]) throws Exception
{
Employee e1 = new Employee(1, "Santhosh Reddy");
Employee e2 = new Employee(2, "Revathi Reddy");
Employee e3 = new Employee(3, "Upendar Reddy");
ArrayList<Employee> list = new ArrayList<Employee>();
list.add(e1);
list.add(e2);
list.add(e3);
for(Employee e:list)
{
System.out.println(e);
}
}

public void setId(int id)
{
this.id = id;
}

public int getId()
{
return id;
}

public void setName()
{
this.name = name;
}

public String getName()
{
return name;
}
}

Output

>java Employee
Employee[id=1, name=Santhosh Reddy]
Employee[id=2, name=Revathi Reddy]
Employee[id=3, name=Upendar Reddy]