|
CHAPTER 14: Blocks and Statements |
|
 Previous |
 Java Language |
 Index |
 Next |
14.11 The do Statement
14.11.1 Abrupt Completion
, 14.11.2 Example
The do
statement executes a Statement and an Expression repeatedly until the value of the Expression is false
.
DoStatement:
do Statement while ( Expression ) ;
The Expression must have type boolean
, or a compile-time error occurs.
A do
statement is executed by first executing the Statement. Then there is a choice:
- If execution of the Statement completes normally, then the Expression is evaluated. If evaluation of the Expression completes abruptly for some reason, the do
statement completes abruptly for the same reason. Otherwise, there is a choice based on the resulting value:
- If the value is true
, then the entire do
statement is executed again.
- If the value is false
, no further action is taken and the do
statement completes normally.
- If execution of the Statement completes abruptly, see S14.11.1 below.
Executing a do
statement always executes the contained Statement at least once.
Abrupt completion of the contained Statement is handled in the following manner:
- If execution of the Statement completes abruptly because of a break
with no label, then no further action is taken and the do
statement completes normally.
- If execution of the Statement completes abruptly because of a continue
with no label, then the Expression is evaluated. Then there is a choice based on the resulting value:
- If the value is true
, then the entire do
statement is executed again.
- If the value is false
, no further action is taken and the do
statement completes normally.
- If execution of the Statement completes abruptly because of a continue
with label L, then there is a choice:
- If the do
statement has label L, then the Expression is evaluated. Then there is a choice:
- If the value of the Expression is true
, then the entire do
statement is executed again.
- If the value of the Expression is false
, no further action is taken and the do
statement completes normally.
- If the do
statement does not have label L, the do
statement completes abruptly because of a continue
with label L.
- If execution of the Statement completes abruptly for any other reason, the do
statement completes abruptly for the same reason. The case of abrupt completion because of a break
with a label is handled by the general rule (S14.6).
The following code is one possible implementation of the toHexString
method (S20.7.14) of class Integer
:
public static String toHexString(int i) {
StringBuffer buf = new StringBuffer(8);
do {
buf.append(Character.forDigit(i & 0xF, 16));
i >>>= 4;
} while (i != 0);
return buf.reverse().toString();
}
Because at least one digit must be generated, the do
statement is an appropriate control structure.
 | © 1996 Sun Microsystems, Inc. All rights reserved. |