Enhanced for - loop or for-each loop
This feature is introduced in Java 5. It is a specially designed loop to retrieve elements of arrays and collections.
For eg: (1)int[ ] x= { 10, 20,30,40};
To print elements of the above array:
Normal loop
for(int i=0; i<x.length; i++)
System.out.println(x[i]);
Enhanced for loop
for(int x1 : x)
System.out.println(x1);
(2) For 2-D arrays
Normal loop
for(int i=0; i<x.length; i++)
{ for (int j=0; j<x[i].length; j++)
{ System.out.println(x[i]);}
}
Enhanced for loop
for(int x1 : x)
{ for( int x2: x1)
{ System.out.println(x2);}
}
The enhanced for loop executes in sequence.ie the counter is always increased by one , whereas in normal for loop you can change the steps as per your wish. eg: doing something like i= i+2;
Comments
Post a Comment