Java for each loop
In this chapter you will learn:
- What is Java for each loop
- How to write for each loop
- Example - for each loop
- Example - for-each style loop to iterate a two-dimensional array
- Example - search an array element with 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 . ja v a 2s .co 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;//from ww w .j a v a 2 s.c o 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;//from w ww . j a va 2s . c om
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.
Next chapter...
What you will learn in the next chapter:
- What is Java while loop
- How to use the basic Java While Loop
- Note for Java while Loop
- Example - Java while loop
- Example - while condition
- Example - while loopbody