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.
int[] scores = { 215, 234, 218, 189, 221, 290}; 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.
for(int score : scores) 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.
Student students[] = new Student[4]; for loops. Shown below is an example of iterating through a two-dimensional (2d) array.
double rates[][] = {{3.45, 5.5, 2.45}, {1.54, 2.89, 3.89}}; 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.
|