Post-Test Loop
Image: Taylor, CC BY-SA 4.0, Wikimedia Commons
In short: A loop whose exit condition is only checked AFTER the first iteration — so the loop body always runs at least once.
In more detail: In Java, do...while is the only post-test loop form. Useful when an action is guaranteed to happen at least once before it’s even checked whether it needs to be repeated — a classic example: a menu prompt that’s shown at least once.
In Depth
The difference between pre-test and post-test is best shown with an extreme case — a condition that’s false from the very start:
int n = 0;
// Pre-test: condition checked first -> runs 0 times
while (n > 0) {
System.out.println("never runs");
}
// Post-test: body executed first, THEN checked -> runs exactly 1 time
do {
System.out.println("runs once anyway");
} while (n > 0);This guarantee of “at least one iteration” makes the post-test loop the right choice whenever an action absolutely has to happen BEFORE it can even be checked whether a repeat is needed — classically for user input, which can only be validated after it’s been entered. In practice, do-while is still significantly rarer in Java code than pre-test forms, because many cases can also be solved with an infinite loop plus break, which some developers find more explicit and readable.
Classic practical example: menu prompt
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1) Restart 2) Save 3) Exit");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Restarting...");
case 2 -> System.out.println("Saved.");
case 3 -> System.out.println("Exiting...");
default -> System.out.println("Invalid choice, please try again.");
}
} while (choice != 3);The menu MUST be shown at least once so the user can even make a choice — a pre-test loop would need an artificial upfront initialization of the exit variable here to achieve the same effect, which makes the code more cumbersome.
Equivalent implementation without do-while
The same logic can always also be reproduced with an infinite loop (while (true)) plus an explicit break at the desired spot — this style allows placing the exit condition in the middle of the loop body, instead of only at the start or end, which is sometimes more flexible than the rigid “body first, then condition” pattern of do-while:
while (true) {
// action
if (conditionMet) break;
}Terminology in other languages
The term “post-test loop” is common in computer science education, in English-language literature it’s usually called a “post-condition loop” or simply a “do-while loop”, after the Java notation. Not every programming language offers this form natively: Python, for example, does entirely without its own post-test loop construct and reproduces the same behaviour via an infinite loop with break, while C, C++, C#, and JavaScript, like Java, come with genuine do-while syntax.
See also: do-while Loop, Pre-Test Loop, Loops