Thursday, 14 August 2014

How to use For Each loop in Java



-> It was introduced in JDK 1.5

-> Its mainly used to traverse the elements from array or collections.

-> The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.


Syntex:

for(data_type variable : array | collection)
{

}


Example :

class ForEachExample1{ 
  public static void main(String args[]){ 
   int arr[]={12,13,14,44}; 
 
   for(int i:arr){ 
     System.out.println(i); 
   } 
 
 }  

     

Output:12
       13
       14
       44

No comments:

Post a Comment