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 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 the result is of type
Boolean, it is subject to unboxing conversion (§5.1.8).If evaluation of the Expression or the subsequent unboxing conversion (if any) completes abruptly for some reason, the
dostatement completes abruptly for the same reason.Otherwise, there is a choice based on the resulting value:
- If the value is
true, then the entiredostatement is executed again. - If the value is
false, no further action is taken and thedostatement completes normally.
- If the value is
-
If execution of the Statement completes abruptly, see §14.13.1.
Executing a do statement always executes the contained Statement at least once.
Example 14.13-1. The do Statement
The following code is one possible implementation of the toHexString method 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.
14.13.1. Abrupt Completion of do Statement
Abrupt completion of the contained Statement is handled in the following manner:
-
If execution of the Statement completes abruptly because of a
breakwith no label, then no further action is taken and thedostatement completes normally. -
If execution of the Statement completes abruptly because of a
continuewith no label, then the Expression is evaluated. Then there is a choice based on the resulting value:- If the value is
true, then the entiredostatement is executed again. - If the value is
false, no further action is taken and thedostatement completes normally.
- If the value is
-
If execution of the Statement completes abruptly because of a
continuewith labelL, then there is a choice:-
If the
dostatement has labelL, then the Expression is evaluated. Then there is a choice:- If the value of the Expression is
true, then the entiredostatement is executed again. - If the value of the Expression is
false, no further action is taken and thedostatement completes normally.
- If the value of the Expression is
-
If the
dostatement does not have labelL, thedostatement completes abruptly because of acontinuewith labelL.
-
-
If execution of the Statement completes abruptly for any other reason, the
dostatement completes abruptly for the same reason.The case of abrupt completion because of a
breakwith a label is handled by the general rule for labeled statements (§14.7).