While Loop
Image: Taylor, CC BY-SA 4.0, Wikimedia Commons
In short: A pre-test loop that runs as long as a condition is true — the number of iterations doesn’t have to be known in advance.
In more detail: The condition is checked BEFORE every iteration; if it’s already false on the first check, the loop body doesn’t run at all. Suitable for cases where the exit condition depends on something dynamic (e.g. user input), not a fixed counter like with the for loop.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}In Depth
Scanner scanner = new Scanner(System.in);
String input;
while (!(input = scanner.nextLine()).equals("stop")) {
System.out.println("You entered: " + input);
}
System.out.println("Done.");Because the condition is checked BEFORE every iteration (“pre-test”), while is especially suitable for cases where the required number of iterations isn’t known in advance and could theoretically even be zero — such as waiting for a specific user input (as above) or processing a file where you don’t know in advance how many lines it has (while ((line = reader.readLine()) != null) { ... }). A common mistake is a condition that never changes within the loop body — the loop then runs forever, until the program is manually terminated or memory is exhausted.
Java has two close relatives of while: do-while (checks the condition AFTER instead of before the iteration, so guarantees at least one iteration) and the for loop (combines initialization, condition, and update into one loop header, common for a known, fixed number of iterations). Practically every while loop can be rewritten as a for loop and vice versa — the choice is usually a matter of readability, not technical possibility.
Infinite loops as a deliberate pattern
Not every while (true) construct is a bug — some programs (e.g. servers that permanently wait for requests) use a deliberate infinite loop and deliberately exit it via break at a specific point within the loop body, instead of formulating the exit condition in the loop header:
while (true) {
String command = scanner.nextLine();
if (command.equals("stop")) {
break; // deliberate exit in the middle of the loop body
}
process(command);
}This is especially useful when the exit condition only becomes known AFTER part of the processing in the loop body, instead of being cleanly formulable up front in the loop header.
Nested while loops and break/continue with labels
For nested loops, a simple break only exits the innermost loop — to deliberately break out of an outer loop, Java supports named labels: outer: while (...) { while (...) { if (condition) break outer; } }. This pattern is rarely needed in practice and is often taken as a sign that the logic could be expressed more clearly through its own method with a regular return.
See also: Loops, For Loop, do-while Loop, Pre-Test Loop, Break/Continue