JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Wednesday, 26 November 2014

For-each loop (Advanced For loop)


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:

13
20
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:

Raju
Hiten
Kiran

No comments:

Post a Comment

Designed By Blogger Templates