For each loop

For-each loop was introduced in java5. for each loop used to traverse array's elements or collection's element. In case of array, there are chances of errors ( accessing out of index element). To avoid programming errors and make code more readable for each loop introduced in java 5.


Syntax of for each loop

    
	for(variable : array | collection) 
{
statement1;
statement2;
..........
..........
statementn;
}

Variable in for-each loop automatically iterate over array or collection. No need to increment the value like for loop.


Example :


// file : all.java 
// www.jgyan.com
 
class all
{
public static void main(String ...arg)
{
int data[]={12,23,34,5,58};
for(int a:data)
System.out.println(a);
}
}
/* output
12
23
34
5
58
*/


for each is advance version of for loop.


Example :


// file: all1.java
// www.jgyan.com
import java.util.*; // For ArrayList class
class all1
{
public static void main(String ...arg)
{
ArrayList data = new ArrayList();
data.add(3);
data.add(7);
data.add(19);
data.add(30);

for(int a:data)
System.out.println(a);
}
}
/*output:
3
7
19
30
*/