Here is a full program showing a countdown, a retry with a cap, and a sentinel-controlled loop, which is the traditional way to read a list of numbers from a user.
final int SECRET = 7;
final int SENTINEL = -1;
final int MAX_GUESSES = 5;
int guess = 0;
int tries = 0;
while (guess != SECRET && tries < MAX_GUESSES) {
tries++;
guess = readGuess();
if (guess == SENTINEL) {
System.out.println("Giving up");
break;
} if (guess == SECRET) {
System.out.println("Correct in " + tries + " tries");
} else {
System.out.println("Wrong, try again");
}
}
A sentinel-controlled loop is worth knowing even though modern Java rarely uses it. The idea is that a special impossible value, here -1, means stop. The user enters numbers until they type the sentinel. It is a classic exam topic and a reasonable way to read an unknown number of values.
For escaping a running loop outright, see the break statement page. For the overview of all four loops and when to pick each, see the looping overview page.
Frequently Asked Questions
What is an entry-controlled loop?
A loop that tests its condition before running the body, so the body may run zero times. Both the for loop and the while loop are entry-controlled. A do-while loop is the opposite, called exit-controlled, and always runs at least once.
How do I prevent an infinite while loop?
Guarantee that something inside the body changes the condition toward false, and do it before any continue that might skip it. If your program appears to hang, the condition and its update are the first two places to look.
When should I use while instead of for?
Use while when you do not know the iteration count, such as reading until end of file, retrying an operation or waiting for a state change. Use for when you are counting, since it keeps the counter, bound and step together in the header.
Why does my while loop never run?
Because the condition was already false on the first test. This is correct behaviour, not a bug. If you need the body to run at least once, use a do-while loop.
Can a while loop have a counter like a for loop?
Yes, but you must declare the counter before the loop and update it inside the body yourself. If that is all you are doing, a for loop is shorter and safer.
Is a while loop slower than a for loop?
No, they compile to effectively the same code. Choose based on clarity rather than speed. A for loop communicates counting better, a while loop communicates repeating until something changes.
What is a sentinel-controlled loop?
A loop that ends when the input matches a special value, usually one that could not be valid data, such as minus one. It is how you read an unknown number of values. Modern Java tends to prefer collections or a stream instead.