CKTIS / Java
do — post-test loop
do — post-test loop: A do statement executes its body before testing the boolean expression after while, so the body runs at least once.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
doA do statement executes its body before testing the boolean expression after while, so the body runs at least once.
Use do-while when the first pass is mandatory, such as retrying input or driving an iterative menu.
The semicolon after while(condition) is part of the syntax and easy to miss; the control mutation must still guarantee termination.
continue in a do-while proceeds to the condition test rather than directly to the body; break exits without another test.
continue still reaches the while test, so the counter reaches 4; only values 3 and 4 contribute to the total 7.
Examples
public class Main {
public static void main(String[] args) {
int number = 0;
int total = 0;
do {
number++;
if (number < 3) continue;
total += number;
} while (number < 4);
System.out.println(number);
System.out.println(total);
}
}
Result
4 7
continue still reaches the while test, so the counter reaches 4; only values 3 and 4 contribute to the total 7.