Java Reference
In-Depth Information
5.4 The while Statement
As we discussed in the introduction of this chapter, a repetition statement (or
loop) allows us to execute another statement multiple times. A while statement is
a loop that evaluates a boolean condition just as an if statement does and exe-
cutes a statement (called the body of the loop) if the condition is true. However,
unlike the if statement, after the body is executed, the condition is evaluated
again. If it is still true, the body is executed again. This repetition continues until
the condition becomes false; then processing continues with the statement after
the body of the while loop. Figure 5.7 shows this processing.
While Statement
switch
(
Expression
)
{
}
Switch Case
The while loop repeatedly executes the specified Statement as long
as the boolean Expression is true. The Expression is evaluated first;
therefore the Statement might not be executed at all. The Expression is
evaluated again after each execution of Statement until the Expression
becomes false.
Example:
while (total > max)
{
total = total / 2;
System.out.println ("Current total: " + total);
}
condition
evaluated
true
false
statement
FIGURE 5.7
The logic of a while loop
 
Search WWH ::




Custom Search