Friday, June 28, 2013

Java 5 Enhanced For Loop

Enhanced For Loop

 This enhanced For loop helps to iterate over an array or collection easily, it reduces the unwanted initialization , condition and increment operation for iterating a complete array or collection 
                  Example :

int[] a=new int[]{4,5,6,7,8,6,4,3};

for(int i=0;i<a.length;i++)
{
System.out.println(i);
}

can be written as (works only in 1.5 and greater version)

for(int i:a)
{
System.out.println(i)
         } 
get trained in new features of java from candid java training

 Enhanced for loop can be used only to iterate over a complete array or collection. we cannot give our own condition in it.

Example using Collections

             ArrayList al=new ArrayList();
                              al.add("hai");
                              al.add("welcome");                              al.add("ewew");

to iterate this ArrayList we can use enhanced for loop

             for(String s:al) 
            {
              System.out.println(s)
            }

Go through our online java tutorial

No comments:

Post a Comment