While Loop
Image: Taylor, CC BY-SA 4.0, Wikimedia Commons
In short: A pre-test loop that repeats a code block as long as a condition is true at the start of every iteration — if the condition is false from the start, the block doesn’t run at all.
In more detail: Unlike the for loop, the while loop is especially suitable when the number of iterations isn’t known in advance — e.g. when waiting for user input or reading a file until its end. The counterpart is the post-test loop (do...while), where the condition is only checked after the first iteration.
In Depth
while (condition) {
// code block
// MUST change the condition somewhere, otherwise an infinite loop
}A typical use case where the number of iterations is only known at runtime:
line = read_next_line(file)
while line != null:
process(line)
line = read_next_line(file)Here you don’t know in advance how many lines the file has — the loop simply keeps running until the exit condition (line == null, i.e. end of file reached) occurs. With a for loop, by contrast, you’d have to know this number in advance or artificially simulate it.
The most common source of error with while loops is forgetting to update the checked condition — if it stays true unchanged, an infinite loop results:
i = 0
while i < 10:
process(i)
# MISSING: i = i + 1 -> infinite loop!Unlike a for loop, where initialization, condition, and update usually sit compactly together on one line, for while the responsibility for the update is left entirely to the programmer and easy to overlook — one reason for is usually the safer choice for a known, fixed number of iterations, while while shows its strength precisely when the number of iterations is unknown.
Deliberate infinite loops
Not every loop with no obvious natural end is a mistake — long-running programs like servers or game main loops (“game loop”) deliberately use an infinite loop (while true:), which is only left via an explicit exit statement (e.g. break) at a specific spot in the code block, instead of formulating the exit condition in the loop header. This makes sense when the exit decision only becomes known in the middle of processing an iteration, not already at the start.
While vs. recursive implementation
Almost every while loop can alternatively be expressed as a recursive function (the function calls itself again with updated state, instead of repeating a loop) — functionally equivalent, but with different practical properties: recursion can exceed the call stack for very many iterations (stack overflow), a loop can’t. Some languages (especially functional languages) optimise certain recursive patterns (“tail-call optimisation”) so this risk disappears — but in many widespread languages (including Java), this optimisation doesn’t exist, which is why while/for is usually preferred over recursion there for simple repetitions.
See also: Loops, Pre-Test Loop, Post-Test Loop, Recursion