Ignora collegamentiHome / Blog

Blog


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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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