for each loop

  1. It is also called as enhanced for loop introduced in 1.5 version.
  2. It is a specially designed loop to retrieve all data items from arrays and collections.

Example:1

int[]  a = {
    10,
    20,
    30,
    40,
    50
};
now we will retrieve elements from this array using normal
for loop and using
for each loop:
    using normal
for loop:
    for (int i = 0; i < a.length; i++) {   
        System.out.println(a[i]);
    }
Using
for each(enhanced
    for) loop
for (int a1: a) {    
    System.out.println(a1);
}


Example-2:

Assume we have a 2 dimensional array like,
int[][]  a = {
    {
        10,
        20,
        30
    },
    {
        40,
        50
    }
};
now we will retrieve elements using normal
for loop and using enhanced
for loop:

 

Using normal
for loop
for (int i = 0; i < a.length; i++) {
    for (j = 0; j < a[i].length; j++) {
        System.out.println(a[i][j]);
    }
}
Using
for each(enhanced
    for) loop
for (int[] a1: a) {
    for (int a2: a1) {
        System.out.println(a2);
    }
}

 

Advantage
For each loop is the best choice to retrieve data items from arrays and collections.
Disadvantages
It is not a general purpose loop. For exa,
for(int i=1;i<5;i++)
{
System.out.println(“SILAN TECHNOLOGY”);
}
Here we can’t write an equivalent code using for each loop directly.
By using normal for loop, we can print array elements either in original order or in reverse order, but by using for each loop we can print array elements only in original order but not in reverse order.
Example,
int[] a={10,20,30,40,50};
for(int i=a.length-1;i>=0;i--)
{
System.out.println(a[i]);
}
Here we can’t write an equivalent code using for each loop. So this is also a disadvantage point.

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment