do-while Loop in Java
A do-while loop is a while loop that checks its condition after the body runs instead of before, which guarantees the body executes at least once no matter what the condition turns out to be. do { body } while (condition); reads almost like a while loop with the parts reordered, but that single difference in when the check happens is the entire reason to reach for one.
The classic use case is a menu or input-validation loop, where the code needs to show the menu — or ask the question — at least once before there's anything meaningful to check the condition against. A plain while loop would need the same logic duplicated once before the loop and once inside it to get that same guaranteed-first-run behavior.
The syntax
do { body } while (condition); runs the body, then checks the condition afterward.
Guaranteed first run
Because the check happens after the body, the body always executes at least once, regardless of the condition's initial value.
Subsequent iterations behave like a while loop
After that first guaranteed run, the condition is checked before every further iteration, exactly like an ordinary while loop.
The semicolon after while
A do-while loop's closing while (condition) needs a semicolon after it, unlike a plain while loop's header.
When it beats a plain while loop
Anywhere the body needs to run once before there's anything to meaningfully check, like showing a menu before asking whether to show it again.
public class DoWhileDemo { public static void main(String[] args) { int attempts = 0; do { attempts++; System.out.println("Attempt " + attempts); } while (attempts < 3); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.