- Here is the Example structure of the for-each loop.
-
// declaration and initialization of a collection
for (declaration : collection) {
// the statements to execute each time the loop iterates, using the declaration
}
- Here is the sequence of steps of the for-each loop.
- The order used is to complete step 1. Then to follow the sequence of step 2 and step 3. Once
step 3 is finished, return to step 2 and repeat the sequence. Note, there is no step 4 since the
increment to the next element is performed and controlled by the for-each loop itself.
step 1
for (step 2) {
step 3;
}
- Here is an example code fragment of a for-each loop that will print all of the values from a
collection.
-
ArrayList <Integer> numbers = new ArrayList <Integer> ();
// use the method *add* to add numbers to the list, for example:
numbers.add(5);
numbers.add(3);
for (Integer number : numbers) {
System.out.println("Number: " + number);
}