Iterating an Array

Prior to Java 5, the only way to iterate the members of an array was to use a for loop and the array’s indexes. For example, the following code iterates over a String array referenced by the variable names:

for (int i = 0; i < 3; i++) { 
    System.out.println("\t- " + names[i]);
}

Java 5 enhanced the for statement. You can now use it to iterate over an array or a collection without the index. Use this syntax to iterate over an array:

for (elementType variable : arrayName)

Where arrayName is the reference to the array, elementType is the element type of the array, and variable is a variable that references each element of the array.

For example, the following code iterates over an array of Strings.

String[] names = { "John", "Mary", "Paul" };
for (String name : names) {
    System.out.println(name);
}

The code prints this on the console.

John
Mary
Paul