The for-each statement was introduced with the release of Java 5. It is sometimes referred to as the enhanced for loop. Advantages of using the for-each statement include:
It is unnecessary to provide end conditions for the counter variable
It is simpler and more readable
The statement provides opportunities for compiler optimization
The use of generics is simplified
The for-each statement is used in conjunction with collections and arrays. It provides an easier way to iterate through each member of an array or class that has implemented the java.util.Iterable
interface. As the Iterable
interface is the super interface of the java.util.Collection
interface, the for-each statement can be used with those classes that implement the Collection
interface.
The syntax of this statement is similar to the regular for statement, except for the contents of its parentheses. The contents include a data type followed by a variable, a colon, and then an array name or collection, illustrated...