Iterative Statement : for-each loop

Iterative Statement : for-each loop

                                 for-each loop(enhanced for loop)

  • for-each loop introduction in 1.5v .
  • it is specially designed to retrieve elements of arrays and collections.
example -; to print elements of one-dimensional arrya.
normal for loop
int[] x={10,20,30,40,50};
for(int i=0;i<x.length;i++)
   System.out.print(x[i]);

for-each loop
int[] x={10,20,30,40,50};
for(int x1:x)
   System.out.print(x1);


example-:to print element of the two-dimensional array.

for-each loop
int[][] arr={{2,2,4},{1,2,4}};
for(int[] a:arr){
   for(int x:a){
         System. out.print(x);
  }
}

normal for loop
int[][] arr={{2,3,5},{1,2,4}};
for(int i=0;i<arr.length;i++){
   for(int j=0;j<arr[i].length;j++){
             System. out.print(arr[i][j]);
   }
}

example-:to print element of the three-dimensional array.
int[][][] arr={{{1,2,3},{3,2,1}}{{4,5,6},{3,1,5}}};
for(int[][] x:arr){
     for(int[] a:x){
        for(int b:a){
             System. out.print(b);
        }
     }
}

  • for each loop best choice is to retrieve arrays and collections but its limitation is it's applicable only for arrays and collections and its not a general proposed loop.
        example-:

            for(int i=0;i<10;i++){
                     System.out.print("Hello");
            }//we can't write equivalent to for-each loop directly 

  • by using the normal for loop we can print elements either in the 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[] x={1,2,3,4,5,6};
            for(int i=x.length-1;i>=0;i--){
                System.out.print(x[i]);
            }//we can't write equivalent to for-each loop directly 




                                                                Iterable(Interface)
 syntax-:
   for(eachitem x:target){
}

  • the target element in the for-each loop should be an iterable object. an object is said to be iterable if and only if the corresponding class implements java.lang.Iterable interface.
  • iterable interface introduced in 1.5v .and it contains only on method public Iterator iterator().
  • all array related classes and collection-implemented classes already implement iterable interface a programmer we are not required to do anything just we should aware the point
Differences between Iterator and Iterable-:

Iterator
  • it is related to collections.
  • we can use to retrieve elements of the collection one by one.
  • present in java.util package.
  • it contains three method (hasNext(),next(),remove()).

Iterable
  •    it is related to for-each loop.
  •    the target element in the for-each loop should be iterable.
  •    it contains one method iterator().
  •    present in java.lang package.
   
Previous Post Next Post

Most Recent