do-while Loop

Runs At Least Once

A do-while loop checks the condition after the block, so the block always runs at least once.

Example

public class Main {
    public static void main(String[] args) {
        int count = 10;
        do {
            System.out.println("do-while ran with count = " + count);
            count++;
        } while (count < 5);   // false, but the body already ran once

        int attempts = 0;
        boolean success;
        do {
            attempts++;
            success = attempts == 3;     // pretend the 3rd try works
            System.out.println("Attempt " + attempts + (success ? " succeeded" : " failed"));
        } while (!success);
    }
}

Output

do-while ran with count = 10
Attempt 1 failed
Attempt 2 failed
Attempt 3 succeeded

while vs do-while

whiledo-while
Condition checkedbefore the bodyafter the body
Minimum runs01
Typical useloop while data existsmenus, retry logic, "ask again" input
Semicolonnone after )required: } while (x);