How to use for-each loop in Java
The for-each construct can be used to hide the index variable and allows to simplify the code. The following program shows how to use the for-each loop to iterate through all the elements of an array of objects of type Person:
public class ForEachExample
{
public static void main(String[] args)
{
// Create an array of objects of type Person
Person[] personArray = { new Person("Smith", 3260),
new Person("Tomas", 1230),
new Person("Alexia", 5290),
new Person("Barbara", 2720),
new Person("Terry", 1260)
};
System.out.println("NAME" + "\t" + "SALARY");
// Print the contents of the array of objects of type Person
for (Person p : personArray)
{
System.out.println(p.ToString());
}
}
}
/*
Simple Java class that represents a type Person
*/
class Person
{
String name;
int salary;
public Person(String n, int s)
{
name = n;
salary = s;
}
public String ToString()
{
return name + "\t" + salary;
}
}
The program returns the following result:
NAME SALARY
Smith 3260
Tomas 1230
Alexia 5290
Barbara 2720
Terry 1260
Category: Java