Java Reference
In-Depth Information
The
while
Statement
The exam objectives state that you should be able to “develop code that implements all
forms of loops and iterators, including while”. A
while statement
is a repetition control
structure that is useful for repeating a block of code an indeterminate number of times.
Figure 3.5 shows the syntax of a
while
statement.
FIGURE 3.5
The syntax of a
while
loop
The while keyword
Parentheses (required)
Curly braces are
required if the body
is more than one
statement.
while (
boolean_expression
) {
//body of loop
}
The body of the loop executes
while the boolean expression is
true.
The following rules apply to a
while
statement:
The value in parentheses must evaluate to a
boolean
expression, either true or false.
If the
boolean
expression is
true
, the body of the loop executes and the
boolean
is
checked again.
If the
boolean
expression is
false
, the loop does not execute and control jumps to the
next statement following the end of the loop.
The body of the loop executes until the
boolean
expression is
false
.
Let's start with a simple example. The following
while
statement prints the
char
s
'A'
to
'H'
on the same line:
3. char c = 'A';
4. while(c <= 'H') {
5. System.out.print(c++);
6. }
The loop executes eight times, and the output is
ABCDEFGH
Search WWH ::
Custom Search