3.12. The for-each statement
Last updated: 23 January 2013.
The for-each statement is a convenient way to iterate over an array or a collection (you will learn about collections later in the tutorials). Unlike the for statement, the for-each statement does not explicitly use an iterator variable. Here is the syntax of the for-each statement:
for(<type> <element> : <array>){
// the statements that are to be executed repeatedly go here
}
// the statements that are to be executed repeatedly go here
}
Syntax explanation:
- type is the data type of the elements contained in the array (or collection).
- element is the current element of the array (or collection). The value of that current element changes at each iteration.
- array is the array (or collection) you want to iterate over.
In the example shown below, the method forEachLoop declares and initializes an array of characters and prints all of its elements to the standard output:
public class JavaLoops {
public void forEachLoop(){
char[] myArray = { 'a', 'b', 'c', 'd', 'e' };
for(char c : myArray){
System.out.println(c);
}
}
}
public void forEachLoop(){
char[] myArray = { 'a', 'b', 'c', 'd', 'e' };
for(char c : myArray){
System.out.println(c);
}
}
}
Create a class named App and call the method forEachLoop:
public class App {
public static void main(String[] args) {
new JavaLoops().forEachLoop();
}
}
public static void main(String[] args) {
new JavaLoops().forEachLoop();
}
}
The output is:
a
b
c
d
e
b
c
d
e
You are here :
JavaPerspective.com >
Beginner Tutorials >
3. Java Basics >
3.12. The for-each statement
Next tutorial : JavaPerspective.com > Beginner Tutorials > 3. Java Basics > 3.13. The while statement
Next tutorial : JavaPerspective.com > Beginner Tutorials > 3. Java Basics > 3.13. The while statement