Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
boolean done = false;

i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}

Here, the initialization and iteration expressions have been moved out of thefor. Thus, parts
of theforare empty. While this is of no value in this simple example—indeed, it would be
considered quite poor style—there can be times when this type of approach makes sense.
For example, if the initial condition is set through a complex expression elsewhere in the
program or if the loop control variable changes in a nonsequential manner determined by
actions that occur within the body of the loop, it may be appropriate to leave these parts of
theforempty.
Here is one moreforloop variation. You can intentionally create an infinite loop (a loop
that never terminates) if you leave all three parts of theforempty. For example:

for( ; ; ) {
// ...
}

This loop will run forever because there is no condition under which it will terminate.
Although there are some programs, such as operating system command processors, that
require an infinite loop, most “infinite loops” are really just loops with special termination
requirements. As you will soon see, there is a way to terminate a loop— even an infinite
loop like the one shown—that does not make use of the normal loop conditional expression.

The For-Each Version of the for Loop


Beginning with JDK 5, a second form offorwas defined that implements a “for-each” style
loop. As you may know, contemporary language theory has embraced the for-each concept,
and it is quickly becoming a standard feature that programmers have come to expect. A for-
each style loop is designed to cycle through a collection of objects, such as an array, in strictly
sequential fashion, from start to finish. Unlike some languages, such as C#, that implement
a for-each loop by using the keywordforeach, Java adds the for-each capability by enhancing
theforstatement. The advantage of this approach is that no new keyword is required, and no
preexisting code is broken. The for-each style offoris also referred to as theenhancedforloop.
The general form of the for-each version of theforis shown here:

for(type itr-var : collection)statement-block

Here,typespecifies the type anditr-varspecifies the name of aniteration variablethat will
receive the elements from a collection, one at a time, from beginning to end. The collection
being cycled through is specified bycollection. There are various types of collections that
can be used with thefor, but the only type used in this chapter is the array. (Other types of
collections that can be used with thefor, such as those defined by the Collections Framework,

92 Part I: The Java Language

Free download pdf