For each loop generally used to handle the elements of collection.Collection is a group of elements. Eg Arrays and java.utli classes(Stack,LinkedList,Vector etc).
For each loop repeatedly executes statements for each of the elements in the collection.Syntax of for-each loop:
for(datatype variable:collection){
Statements;
}
Example of "for each loop" using array:
Program1:
class ForEachLoop1
{
public static void main(String args[])
{
int arr[]={13,20,30,40};
for(int i:arr)
{
System.out.println(i);
}
}
}
O/P:
1320
30
40
Example of "for-each loop" using Linked List:
Program2:
import java.util.*;
class ForEachLoop2
{
public static void main(String args[])
{
LinkedList<String> list=new LinkedList<String>();
list.add("Raju");
list.add("Hiten");
list.add("Kiran");
for(String s:list)
{
System.out.println(s);
}
}
}
O/P:
RajuHiten
Kiran
No comments:
Post a Comment