Careeroza
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
| while | do-while | |
|---|---|---|
| Condition checked | before the body | after the body |
| Minimum runs | 0 | 1 |
| Typical use | loop while data exists | menus, retry logic, "ask again" input |
| Semicolon | none after ) | required: } while (x); |