Pages

Adhexa

Wednesday, October 7, 2015

For-each loop

For-each loop 

The for-each loop is mainly used to traverse array or collection elements. For-each loop eliminates the possibility of bugs and makes the code more readable.

Syntax of for-each loop:

for(data_type variable : array | collection){}  

Simple Example of for-each loop for traversing the array elements:

    
class ForEachExample1{  
  public static void main(String args[]){  
   int arr[]={1,2,3,4,5};  
  
   for(int i:arr){  
     System.out.println(i);  
   }  
  
 }   
}