Quick Reach
The Foreach loop in Java
A few main points about the foreach loop:
- The foreach loop was introduced in JDK 1.5.
- The foreach loop enables to traverse through the arrays sequentially, without using the index variable.
- The foreach is often used in arrays.
- The foreach loop is not used like in other programming languages by using the “each” keyword. It is just like the for loop but acts like the “foreach”, See the examples below.
Example of using Java foreach loop
The following example uses the split method of Java string and breaks a string completely by a regular expression. The example uses foreach Java loop to display array items created after the split method.
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class loop_example {
public static void main(String []args) {
String Strex;
Strex =“name is: Mike and age is: 30 and salary is: $5000”;
for (String Strsplit: Strex.split(” and “)){
System.out.println(Strsplit);
}
}
}
|
The output will be:
name is: Mike
age is: 30
salary is: $5000
A foreach loop example with an array
This example declares an array with five elements and then displays “each” array element by using the foreach loop.
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class loop_example {
public static void main(String []args) {
int arrforeach[] = {1,2,3,4,5};
for (int i = 0; i < arrforeach.length; i++) {
System.out.println(arrforeach[i] + ” “);
}
// }
}
}
|
The output will be:
1
2
3
4
5
Also see: for loop
Leave A Comment?