7.1 while and do-while Loops

Key Takeaways

  • while checks its condition before entering the body. do-while starts with the body and checks its condition after normal completion or a continue targeting it.

  • Both while and do-while require an expression that evaluates to boolean or unboxed Boolean; numeric expressions such as while (1) fail compilation

  • A do-while loop requires a trailing semicolon immediately after the closing parenthesis of while (condition); omitting it causes a syntax error

  • Variables declared inside a do block go out of scope at its closing brace and cannot be referenced inside the trailing while condition

  • A reachable while (false) has an unreachable body and fails compilation. A reachable while (true) can complete normally only if a reachable break exits it.

Last updated: November 2026

7.1 while and do-while Loops

Iteration lets a program repeat a block of work until a state changes. This section covers the pre-test while loop and post-test do-while loop mapped to Oracle Java SE 8 Programmer I (1Z0-808) Domain 5 (Using Loop Constructs). Exam questions frequently combine condition evaluation order with variable scoping, missing braces, and compile-time reachability rules.

The Pre-Test while Loop

The while loop evaluates its controlling expression before executing the loop body:

while (booleanCondition) {
    // Loop body: executes 0 or more times
}

If booleanCondition evaluates to false on the very first check, the JVM skips the body entirely and resumes at the next statement after the loop. That makes while ideal when the required number of repetitions is unknown beforehand and zero iterations is valid.

int retries = 0;
while (retries < 3) {
    System.out.println("Attempt " + retries);
    retries++;
}
System.out.println("Final retries: " + retries);

Exact output:

Attempt 0
Attempt 1
Attempt 2
Final retries: 3

When retries reaches 3, retries < 3 becomes false, so the loop terminates and control moves to the final println.

Mandatory boolean Condition Rule

Unlike C or C++, Java does not treat 0 as false or non-zero integers as true. The condition inside while (...) or do ... while (...) must have type boolean or java.lang.Boolean (which Java unboxes automatically, throwing a NullPointerException at runtime if the Boolean reference is null).

int count = 1;
// while (count) { }       // Compile error: int cannot be converted to boolean
// while (count = 5) { }   // Compile error: assignment yields int 5, not boolean

boolean active = false;
while (active = true) {    // Compiles. Assigns true before entering the body.
    System.out.println("Running");
    break;                 // Without break, this would be an infinite loop
}

Warning

Watch closely for single = inside a loop condition! If the variable on the left is boolean, while (flag = true) compiles cleanly because the assignment expression evaluates to true. Check the body for an exit, since the condition itself never stops the loop.

Single-Statement and Missing-Brace Traps

Braces {} are technically optional when a loop body contains only one statement. However, omitting braces is one of the most common sources of exam bugs:

int i = 0;
while (i < 3)
    System.out.println(i); // Only this line is inside the loop!
    i++;                   // Outside the loop despite indentation -> infinite loop!

Because Java ignores indentation, i++ executes after the loop finishes—which never happens because i remains 0. An equally subtle error occurs when a stray semicolon immediately follows the while header:

int n = 0;
while (n < 3); {
    n++;
}
System.out.println(n);

Here, the semicolon ; acts as an empty statement that forms the entire loop body. Since n is never modified by that empty statement, while (n < 3); spins forever and { n++; } is never reached.


The Post-Test do-while Loop

A do-while loop enters its body first. After the body completes normally, or a continue targets the loop, it checks the condition:

do {
    // Loop body: executes at least 1 time
} while (booleanCondition);

Notice two critical syntactic rules:

  1. Even if booleanCondition starts as false, the body executes at least once.
  2. The trailing semicolon ; after while (booleanCondition); is mandatory. Omitting it causes a compile-time error (';' expected).
int x = 10;
do {
    x += 5;
    System.out.println("Inside do-while: " + x);
} while (x < 10);
System.out.println("After do-while: " + x);

Exact output:

Inside do-while: 15
After do-while: 15

Even though x < 10 is already false when x starts at 10, the body runs once, increments x to 15, tests 15 < 10 (false), and exits.

The do-Block Variable Scope Trap

A favorite exam trick declares the loop control variable inside the do block and then tests it in the trailing while condition:

do {
    int value = 1;
    value++;
} while (value < 5); // Compile error: cannot find symbol 'value'

The scope of value starts at its declaration inside { ... } and ends at the closing brace } before the while (value < 5); clause is evaluated. To test a variable in the while condition, declare it outside the loop:

int value = 1;
do {
    value++;
} while (value < 5);
System.out.println(value); // Prints 5

Unreachable Code Compiler Traps

Under the Java Language Specification (JLS §14.21), statements that are unreachable under the language’s formal reachability rules cause a compile-time error (error: unreachable statement). How the compiler treats while and do-while depends on whether the condition is a compile-time constant expression.

// 1. Constant false in while -> COMPILE ERROR (unreachable statement)
// while (false) { System.out.println("Never"); }

// 2. Final constant false in while -> COMPILE ERROR (unreachable statement)
final boolean ALWAYS_OFF = false;
// while (ALWAYS_OFF) { System.out.println("Never"); }

// 3. Non-final variable false -> COMPILES! Compiler does not track runtime value
boolean keepRunning = false;
while (keepRunning) {
    System.out.println("Skipped at runtime");
}

// 4. Special JLS exception: if (false) COMPILES for conditional compilation
if (false) {
    System.out.println("Valid conditional compilation");
}

Constant true loops create the opposite reachability trap—making code after the loop unreachable if there is no reachable break:

while (true) {
    System.out.println("Forever");
}
// System.out.println("Done"); // Compile error: unreachable statement

A reachable break that exits the loop can make the following statement reachable. A return exits the method and does not make the following statement reachable. Similarly, do { System.out.println("Once"); } while (false); compiles cleanly because the body executes once and the statement after the loop is reachable, whereas do { ... } while (true); without break makes any following statement unreachable.

Comparing while and do-while

Featurewhile (cond) { ... }do { ... } while (cond);
Condition evaluationPre-test (before body)Post-test (after body)
Minimum iterations01
Trailing semicolonNot used (a stray ; creates an empty body)Mandatory after while (cond);
Variable declared inside bodyOut of scope in while (cond)Out of scope in while (cond);
Constant false conditionCompile error (unreachable statement)Compiles; body executes once
Constant true without breakStatements after loop fail compilationStatements after loop fail compilation

Tip

When tracing while and do-while questions on the exam, check three items in order before tracing numbers: (1) does do-while end with ;, (2) are all condition variables declared before the loop block, and (3) are there any compile-time constant true/false conditions creating unreachable statements?

Test Your Knowledge

What is the result of compiling and running the following Java code?

public class LoopScope {
    public static void main(String[] args) {
        do {
            int count = 0;
            count++;
            System.out.print(count);
        } while (count < 3);
    }
}
A

123

B

111

C

Compilation fails because count is out of scope in the while condition

D

The code compiles and enters an infinite loop

Test Your Knowledge

What does the following code snippet print?

int x = 5;
do {
    x++;
} while (x < 5);
System.out.println(x);
A

6

B

5

C

4

D

Nothing; compilation fails due to an unreachable condition

Test Your Knowledge

Which code snippet FAILS to compile under Java SE 8?

A

boolean flag = false; while (flag) { System.out.println("A"); }

B

if (false) { System.out.println("B"); }

C

do { System.out.println("C"); } while (false);

D

final boolean run = false; while (run) { System.out.println("D"); }

Sections you finish are checked off in the contents.