The for-each loop or enhanced for loop introduced in JDK 1.5 is very useful in iterating through the elements of the array. This for loop simplifies the iteration of elements in an array.
Normally if we will do the following to iterate through an array.
But there are few places in this for loop, where we could make mistakes. For e.g., we could start from i = 1 instead of i = 0 or use the condition to i <= scores.length instead of i < scores.length or forget to call i++. We can rewrite the for loop using the enhanced version as shown below.
Here the variable score has to be of the same type as the type of the array elements. We can iterate through arrays of any type. We can also iterate through arrays of references. Below we have iterated through the objects of Student class.
We can also nest these kind of for loops. Shown below is an example of iterating through a two-dimensional (2d) array.
This form of for loop is very useful when we are not concerned about the indices, but only interested in the elements on the array.