Java Reference
In-Depth Information
}
I have simply transferred the operation of incrementing i from the for loop control expression to the
loop body. The for loop works just as before. However, this is not a good way to write the loop, as it
makes it much less obvious how the loop counter is incremented.
TRY IT OUT: The Collection-Based for Loop
You can't do a whole lot with the collection-based for loop yet. This will come into its own later in the
book, especially after Chapter 14, and you will learn more about what you can do with it in the next
chapter. One thing that it does apply to and that you have learned something about is an enumeration.
Here's how you could apply the collection-based for loop to iterate through all the possible values in an
enumeration:
public class CollectionForLoop {
enum Season { spring, summer, fall, winter }
// Enumeration type
definition
public static void main(String[] args) {
for(Season season : Season.values()) {
// Vary over all
values
System.out.println(" The season is now " + season);
}
}
}
CollectionForLoop.java
This generates the following output:
The season is now spring
The season is now summer
The season is now fall
The season is now winter
How It Works
The season variable of type Season that appears in the first control expression between the parentheses
for the for loop is assigned a different enumeration constant value in each iteration of the loop. The
second control expression, following the colon, identifies the collection that is the source of values for
the variable declared in the first control expression. In this case it is an enumeration, but, in general, there
are other collections you can use, as you see in Chapter 14. In the next chapter you will learn about arrays
where both forms of the for loop can be used.
Search WWH ::




Custom Search