For each in java
Feb 27, 2009 by mohamed hanoosh
Java has a for loop, but it didn't have a for each functionality. From jdk5.0 onwards they have added for each functionality in Java.
Given an array, a loop variable can select each element of the array in each iteration.
In the above example values is an array of integers. i is an iterator(a variable used for traversing through the elements). In the first iteration i will take value 2 , then it next iteration value 4 and so on until the entire array elements are used.
public class Example{
public static void main(String args[]) throws Exception {
int[] values = { 2,4,6,8,10,12,14,16,18,20 };
for( int i : values)
{
System.out.println(i);
}
}
}
Given an array, a loop variable can select each element of the array in each iteration.
In the above example values is an array of integers. i is an iterator(a variable used for traversing through the elements). In the first iteration i will take value 2 , then it next iteration value 4 and so on until the entire array elements are used.