Java for each loop
Description
The for each
loop iterates elements in a sequence without using the loop counter.
Syntax
The syntax of for each
loop is:
for (type variable_name:array){
}
The type
must be compatible with the array
type.
Example
public class Main {
public static void main(String args[]) {
String[] arr = new String[]{"java2s.com","a","b","c"};
for(String s:arr){
System.out.println(s);//w ww.j a v a2 s. c o m
}
}
}
The output:
Example 2
The following code uses the for-each
style loop to iterate a two-dimensional array.
public class Main {
public static void main(String args[]) {
int sum = 0;// w w w.ja v a2 s. co m
int nums[][] = new int[3][5];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 5; j++){
nums[i][j] = (i + 1) * (j + 1);
}
}
// use for-each for to display and sum the values
for (int x[] : nums) {
for (int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
The output from this program is shown here:
Example 3
for-each
style loop is useful when searching an element in an array.
public class Main {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;//www . ja v a 2 s .c o m
boolean found = false;
// use for-each style for to search nums for val
for (int x : nums) {
if (x == val) {
found = true;
break;
}
}
if (found)
System.out.println("Value found!");
}
}
The code above generates the following result.