The for-each(Advance for loop) loop introduced in Java5. It is mainly used to traverse array or
collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and
makes the code more readable. we don?t need to traverse elements manually.
===========================Syntax of for-each loop:=============================
for(data_type variable : array | collection){}
==============================Sample code:===================================
++++++++++++++++++++++Example to traverse Array Elements:+++++++++++++++++++++
class ForEachArraay{
public static void main(String args[]){
int arr[]={11,14,13,15};
for(int i:arr){
System.out.println(i);
}
}
}
Output:
11
14
13
15
++++++++++++++++++++++Example to traverse List Elements:+++++++++++++++++++++
import java.util.*;
class ForEachArrayList{
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("Garima");
list.add("anyforum.in");
list.add("Sailesh");
for(String s:list){
System.out.println(s);
}
}
}
Output:
Garima
anyforum.in
Sailesh
5