Menu
Topics Index
...
`


Array - Overview >
Siva Nookala - 14 Mar 2016
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(int i = 0; i < scores.length; i++)
{
    int score = scores[i];
    System.out.print(score + "  ");
}
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.
for(int score : scores)
{
    System.out.print(score + "  ");
}
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.
Student students[] = new Student[4];
...
for(Student student : students)
{
    student.print();
    ...
}
We can also nest these kind of 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}};

for(double[] yearly_rates : rates)
{
    for(double rate : yearly_rates)
    {
        System.out.print(rate + " ");
    }
    System.out.println();
}

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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.