foreach loop in java .

In this session i have discussed foreach loop in Java .


The foreach loop is introduced in java5 . It is very similar to other loop like for , while , do while . It is another way of traversing the array .

* It is start with for keyword like normal for loop .

* There is no any initialization , condition , and increment/decrement .

* There is a variable their type is same as base type of array or collection classes (discuss later) followed by the colon and then array name .

Foreach syntax

    for(var type : array){
     
       //body of loop
    }
    

Example : Write a java program that demonstrate the foreach loop .

    class A{

        public static void main(String args[]){

            int arr[]={10,20,30,40,50};
            for(int i:arr){

                System.out.print(i+" ");
            }
        }
    }
    
    OUTPUT : 10 20 30 40 50
    

Welcome to AndroidATPoint.

back image                     next image