CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING
The enhanced for syntax is also called “for each”. I dislike that, because other languages (such as
Perl) have an actual foreach keyword. Java has the notion of “for each of these items, run the following
code”, but it does not have an actual foreach keyword. Consequently, I prefer to call it the “enhanced
for.” It got the name when it was introduced in Java 5. Before Java 5, only the basic for structure was
available to Java developers.
Listing 5-12. Enhanced for syntax example
int[] compassPoints = {22, 77, 144, 288};
for (int i: compassPoints) {
System.out.println(compassPoints[i] + " degrees is (very roughly) " +
Direction.findCardinalDirection(compassPoints[i]));
}
Listing 5-12 does the same thing as Listing 5-9.
One last thing that every Java developer should know about a for loop is that it is just a shortcut for
a while loop. That is, every for loop can be rewritten as a while loop. Let's turn the loop from Listing 5-9
into a while loop in Listing 5-13.
Listing 5-13. Turning a for loop into a while loop
int i = 0;
while (i < compassPoints.length) {
System.out.println(compassPoints[i] + " degrees is (very roughly) " +
Direction.findCardinalDirection(compassPoints[i]));
i++;
}
Listing 5-13 does the same thing as Listing 5-9 and 5-12. (You can almost always find multiple ways
to do the same thing in most programming languages, including Java.)
While loops
As we just learned, for loops deal with a specific case of the more general purpose served by while loops.
for loops (usually) deal with things that can be counted. while loops continue to loop as long as
something is true. A while loop has only one argument: an expression that can be evaluated as true or
false.
Before we go any further, let's look at the simplest possible while loop, as shown in Listing 5-14.
Listing 5-14. A simple while loop
while (counter < 10) {
System.out.println(counter);
}
A while loop does not have an explicit initialization variable or an increment statement; you must
provide that functionality yourself. (One of the reasons for the invention of the for loop was to put all
three parts of a loop – initialize, test, and increment – in a single spot.) Though both initialization and
increment often appear near (for initialization) or within (for incrementing) while loops, they are not
part of the while loop syntax, as they are in for loops. So let's look at a more complete example, which
includes initialization and incrementing, in addition to the test (see Listing 5-15).