Java Reference
In-Depth Information
The
do
Statement
The exam objectives state that you should be able to “develop code that implements all
forms of loops and iterators, including do.” A
do statement
, also referred to as a
do-
while
loop, is a repetition control structure that is useful for repeating a block of code an
indeterminate number of times, but at least once. A
do-while
loop is declared using the
do
keyword. Figure 3.6 shows the syntax of a
do
statement.
The syntax of a
do
statement
FIGURE 3.6
Curly braces are
required if the body
is more than one
statement.
The body of the loop
executes while the
boolean expression
is true.
The do
keyword
do {
//body of loop
} while(
boolean_expression
);
Semicolon
The while keyword
Parentheses (required)
The following rules apply to a
do
statement:
The body of the loop executes once before the
boolean
expression is tested.
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 again, and then the
boolean
is checked again.
If the
boolean
expression is
false
, the loop does not execute again and control jumps
to the next statement following the end of the loop.
Just like a
while
loop, the body of the
do
loop executes until the
boolean
expression is
false
.
Don't forget the semicolon after the
boolean
expression — it's easy to miss!
The following simple example prints out the numbers
1
to
10
:
3. int y = 1;
4. do {
5. System.out.print(y++ + “ “);
6. }while(y <= 10);
Search WWH ::
Custom Search