The while loop is one of the fundamental types of loops in Java. It is an entry-controlled loop, meaning the condition is checked before the body of the loop is executed even once.
<aside> <img src="/icons/orbit_gray.svg" alt="/icons/orbit_gray.svg" width="40px" />
Formal Definition
A while loop repeatedly executes a block of statements as long as the specified test condition evaluates to true. The loop terminates (stops executing) when the test condition becomes false.
</aside>
Real-World Analogy
Imagine filling a bucket with water from a tap:
while Loop Logic: While (The bucket is NOT full) $\rightarrow$ Scoop water and pour it in.
while LoopsThe basic structure of a while loop is as follows:
Initialization Expression(s)
while (Test Condition) {
// Body of the loop
Update Expression(s)
}
true.{}) that are executed repeatedly.false, leading to an infinite loop.for Loops| Feature | while Loop | for Loop |
|---|---|---|
| Type | Entry-Controlled | Entry-Controlled |
| Purpose | Best when the number of iterations is NOT known beforehand (e.g., reading user input until a specific keyword is entered). | Best when the number of iterations IS known beforehand (e.g., running 10 times, printing a table up to 20). |
| Syntax | Initialization is separate. | All three components are combined into one line. |
| Components | Initialisation; while (Condition) {... Update;} | for (Initialisation; Condition; Update) {...} |
| Risk | High risk of an infinite loop if the update expression is forgotten. | Lower risk of an infinite loop as the structure prompts for all components. |
The following program demonstrates the use of a while loop to print numbers from 1 to 5.