Java Reference
In-Depth Information
the loop body has been executed. This is what gives a while loop its indefinite character—the
reevaluation process. If the condition evaluates to true , then the body is executed; and once it
evaluates to false , the iteration is finished. The loop's body is then skipped over and execu-
tion continues with whatever follows immediately after the loop. Note that the condition could
actually evaluate to false on the very first time it is tested. If this happens, the body won't be
executed at all. This is an important feature of the while loop: the body might be executed zero
times, rather than always at least once.
Before we look at a proper Java example, let's look at a pseudo-code version of the key hunt
described above, to try to develop a feel for how a while loop works. Here is one way to express
the search:
while( the keys are missing ) {
look in the next place
}
When we arrive at the loop for the first time, the condition is evaluated and the keys are miss-
ing. That means we enter the body of the loop and look in the next place on our mental list.
Having done that, we return to the condition and reevaluate it. If we have found the keys, the
loop is finished and we can skip over the loop and leave the house. If the keys are still missing,
then we go back into the loop body and look in the next place. This repetitive process continues
until the keys are no longer missing. 1
Note that we could equally well express the loop's condition the other way around, as follows:
while( not (the keys have been found) ) {
look in the next place
}
The distinction is subtle—one expressed as a status to be changed and the other as a goal that has
not yet been achieved. Take some time to read the two versions carefully to be sure you understand
how each works. Both are equally valid and reflect choices of expression we will have to make
when writing real loops. In both cases, what we write inside the loop when the keys are finally
found will mean the loop conditions “flip” from true to false the next time they are evaluated.
Exercise 4.29 Suppose we express the first version of the key search in pseudo-code as
follows:
boolean missing = true;
while(missing) {
if( the keys are in the next place ) {
missing = false;
}
}
1 At this stage, we will ignore the possibility that the keys are not found, but taking this kind of possibility
into account will actually become very important when we look at real Java examples.
Search WWH ::




Custom Search