When should you use a for loop, a while loop and a do-while loop in Java, and how do you choose between them?
All three of them repeat a block of code. They differ in how they decide when to stop, and that is the whole of the choice.
Use a for loop when you know how many times you want to go round before you start. A counter, a limit and a step all live in one place at the top, so the shape of the loop is visible at a glance. A loop over an array index, a loop that runs a fixed number of times, and a loop over the items of a list are all for loops in practice.
Use a while loop when you do not know the number of rounds in advance. The condition is the only thing that matters, and the loop keeps going while it stays true. A loop that reads lines until the input ends, and a loop that keeps searching until it finds something, are while loops.
Use a do-while loop when the body has to run at least once before you can even ask the question. A menu that always shows its options before it reads the choice is the standard example.
public class Main {
public static void main(String[] args) {
// A for loop: the count is known before we start.
for (int index = 1; index <= 3; index++) {
System.out.println("for : round " + index);
}
// A while loop: we keep going while the condition is true.
int count = 3;
while (count > 0) {
System.out.println("while : round " + count);
count = count - 1;
}
// A do-while loop: the body always runs at least once.
int attempt = 0;
do {
System.out.println("do : attempt " + attempt);
attempt = attempt + 1;
} while (attempt < 3);
}
}
There is one more thing to think about, and it is the one that trips people up. In a while loop and a do-while loop, if you forget to move the counter along inside the body, the loop never ends. In a for loop, the step is written in the header where you cannot lose it.
The next question in this topic looks closely at the difference between a while loop and a do-while loop.