Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

The while and do-while statements

Reference for Java while and do-while loops: when the condition is checked, running at least once, infinite loops, reading input and common mistakes.

while repeats its body as long as a boolean condition is true. The condition is checked before every iteration, so the body may run zero times. do-while checks the condition after the body, so the body always runs at least once.

Use these loops when you do not know in advance how many iterations you need: reading until the input ends, retrying until success, or converging on a result.

Java
while (condition) {
    body
}

do {
    body
} while (condition);

Try it

Java while: zero or more times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java do-while and breaking out of an endless loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
while (booleanExpression) statement
do statement while (booleanExpression);
Part Description
booleanExpression Must be boolean or Boolean. For while it is tested before each iteration, for do-while after each.
statement A single statement or a block.

Usage notes

  • Change something in the body. If nothing in the loop can make the condition false, you have an infinite loop. Typical cause: forgetting the increment.
  • do-while ends with a semicolon after the condition; while does not.
  • while (true) is a common idiom for event loops and retry logic; leave it with break, return or a thrown exception. The compiler treats code after a loop with a constant true condition (and no break) as unreachable.
  • Variables used in the condition of do-while must be declared outside the body, because the body's scope has ended by the time the condition is evaluated.
  • continue in a do-while jumps to the condition check, not to the start of the body.
  • Counting loops are easier to read with for; collection traversal with the for-each loop.
  • Busy-waiting (while (!flag) {}) burns CPU and, without volatile or other synchronization, may never see the change made by another thread.
  • Iterator style loops: while (it.hasNext()) is the explicit form of the for-each loop and allows it.remove().