While and do-while
What you will learn
A while loop repeats work as long as a condition holds. A do-while loop checks its condition after running the body, which makes it useful when the first action must happen before the decision to repeat.
public class Main { public static void main(String[] args) { int remaining = 3; while (remaining > 0) { System.out.println("Pack " + remaining); remaining--; } }}Expected output:
Pack 3Pack 2Pack 1Each iteration consumes one item. The count reaches zero and the next condition check stops the loop.
How it works
Use while (condition) { ... } when the initial state may require no work. Use do { ... } while (condition); when at least one attempt is appropriate. The semicolon at the end of do-while is required. Keep the condition, changing state and stopping rule close together. For a finite counting task, choose a nonnegative remaining count and decrease it on every iteration. For a retry task, set an explicit maximum number of attempts even if success is expected. A real input loop also needs a rule for end-of-input; this chapter uses only fixed local values so it never waits for a user.
public class Main { public static void main(String[] args) { int inspections = 0; boolean needsAnother = false; do { inspections++; System.out.println("Inspect"); } while (needsAnother && inspections < 3); System.out.println(inspections); }}Expected output:
Inspect1The first inspection happens before the condition is checked. The false flag prevents another iteration.
Check a boundary or unusual input
public class Main { public static void main(String[] args) { int attempts = 0; boolean ready = false; while (!ready && attempts < 3) { attempts++; ready = attempts == 2; // Simulated result, not a network request. } System.out.println(attempts); System.out.println(ready); }}Expected output:
2trueA fixed fixture simulates success on the second attempt; the limit of three also protects the failure path.
Common mistakes
If the body never changes a state involved in the condition, the loop may never terminate. Before running a while loop, identify what moves toward the stopping condition. If the task is already complete initially, a do-while may do unwanted work. Prefer a while loop when zero iterations must be possible.
Try it yourself
A shelf has n items (0–10). Remove up to two items per iteration until empty; count the number of removal rounds. Use while, never let remaining become negative, and print the round count. Test n = 5, 0, 1 and 10.
Save each example independently as Main.java. Compile with javac Main.java and run with java Main. Local Java practice only; automatic ByteMind Java grading is not established.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
While and do-while — knowledge check
Apply while and do-while to examples and boundary conditions.
If the condition is initially false, how many times does a while body execute?
Which loop checks its condition after its first body execution?
What is wrong with while (remaining > 0) when remaining is positive and never changes?
Why add attempts < 3 to a retry condition?
Which construct best handles an already empty queue without processing any item?