You’ve seen for loops for cases where you know (or can easily express) the number of iterations you need. But sometimes, you want to keep looping as long as a certain condition remains true—without necessarily knowing how many times that will be. In Java, there are two “indefinite loops” for that scenario: while and do-while. They both run until their condition becomes false, but they differ slightly in when the condition is checked.
Notice we have the same four elements as a for loop: initialization (i = 0), condition (i < 5), the loop body, and an update (i++). One common pitfall is forgetting the update, which can cause an infinite loop.
Unlike while, a do-while loop checks the condition after running the body once. This guarantees the loop body runs at least once, no matter what. Its syntax is:
Readability is enhanced when the loop structure matches the logical flow. A do-while clearly signals that the code inside runs once before checking, reducing cognitive load.
// Using while
System.out.print("Enter positive number: ");
int num = in.nextInt();
while (num <= 0) {
System.out.print("Invalid. Enter positive: ");
num = in.nextInt();
}
A do-while isn’t suitable here as we don’t want to process invalid input. Conversely, for a menu:
Subsection4.3.4Interactive Exercises: While & Do-While
Let’s solidify your understanding with a few practice exercises. Each focuses on fixing or writing a small loop, highlighting common usage patterns or pitfalls.
Exercise 3: The code below aims to print "Hello!" exactly once using a do-while loop. But it’s missing the correct update or condition. Fix it so it prints "Hello!" once and stops.
Both rely on an effective update step to avoid infinite loops. Next up, we’ll learn how to combine these loops with arrays to handle sets of data more elegantly.