Java Do While Loop

The do/while loop is a close cousin of the while loop with one important twist: it always runs the body at least once before it checks the condition. This makes it perfect for situations where you need to do something first and then decide whether to repeat.

How do/while is different

A regular while loop checks the condition at the top, so if the condition is false from the start, the body never runs. A do/while loop flips that order. It runs the body first and checks the condition at the bottom, guaranteeing at least one execution.

Basic do/while syntax

int i = 0;

do {
  System.out.println("Value: " + i);
  i++;
} while (i < 3);

// Output:
// Value: 0
// Value: 1
// Value: 2
Note: Do not forget the semicolon after the closing while condition. Unlike a normal while loop, a do/while statement ends with a semicolon.

When at-least-once matters

Compare the two loops below. Both have a condition that is false right away, but they behave very differently. The while loop prints nothing, while the do/while loop still prints one line because its check happens after the body.

Same false condition, different result

int n = 10;

while (n < 5) {
  System.out.println("while ran");
}

do {
  System.out.println("do/while ran once");
} while (n < 5);

// Output:
// do/while ran once

This is why do/while fits menus and prompts so well: you want to show the menu at least once, then repeat only if the user has not chosen to quit.

  • The body runs before the condition is ever tested.
  • It is ideal for input validation and menu screens.
  • You still need an update step to avoid an infinite loop.
  • The condition line ends with a semicolon.
Featurewhiledo/while
Condition checkedBefore the bodyAfter the body
Minimum runs01
Ends with semicolonNoYes
Note: Reach for do/while only when running the body once no matter what is genuinely useful. If a zero-run outcome is fine, a plain while loop is easier to read.