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.
while (condition) { body } do { body } while (condition);
Try it
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.
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
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-whileends with a semicolon after the condition;whiledoes not.while (true)is a common idiom for event loops and retry logic; leave it withbreak,returnor a thrown exception. The compiler treats code after a loop with a constanttruecondition (and nobreak) as unreachable.- Variables used in the condition of
do-whilemust be declared outside the body, because the body's scope has ended by the time the condition is evaluated. continuein ado-whilejumps 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, withoutvolatileor other synchronization, may never see the change made by another thread. Iteratorstyle loops:while (it.hasNext())is the explicit form of the for-each loop and allowsit.remove().