while with a condition
while (true) needs a break to stop. A loop can instead have a real condition: it's checked before every round, and the loop ends the first time that check finds it false.
int number = 1;
while (number <= 5) {
System.out.println(number);
number++;
}
System.out.println("Done, number is now " + number);
1
2
3
4
5
Done, number is now 6This is a counting loop, and it has three parts:
- a variable set before the loop (
int number = 1;), - a condition that decides whether another round runs (
number <= 5), - a change inside the loop that moves toward the end (
number++).
Forget the third part and number stays 1 forever: the condition never turns false.
When the loop should end at a known point, a condition says so right at the top. while (true) with break suits loops that end on something the loop reads, like a word such as end.