Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

while / do-while

Repeats a block while a condition is true; do-while runs it at least once.

Available since: Java 1.0

Syntax

while (condition) { … }  /  do { … } while (condition);

Examples

A loop with an unknown number of repetitions:

void main() {
    int n = 100;
    int steps = 0;
    while (n > 1) {
        n /= 2;
        steps++;
    }
    IO.println(steps);
}

Output:

6

do-while checks the condition after the body:

void main() {
    int i = 10;
    do {
        IO.println("runs once: " + i);
    } while (i < 5);
}

Output:

runs once: 10

Notes

If the condition never becomes false, the loop runs forever. An endless loop with an exit condition is written as while (true) { ... if (done) break; }.

See also

  • for — A loop with a counter, or iteration over every element of an array or collection (for-each).
  • break / continue — break exits a loop, continue jumps to the next iteration; a label lets you leave a nested loop.

In the tutorial

  • Loops — Loops in Java: while, do-while, for and for-each over an array.

Thanks for reading!

Donate to the site — we work hard for you.