While Loops in Java

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:

Syntax of while Loops

The basic structure of a while loop is as follows:

Initialization Expression(s)
while (Test Condition) {
    // Body of the loop
    Update Expression(s)
}

Key Components:

  1. Initialization: Setting the initial value of the loop control variable. This is done outside the loop.
  2. Test Condition (or Loop Condition): A boolean expression (e.g., $i < 10$) that is evaluated before each iteration. The loop continues only if this is true.
  3. Loop Body: The statements enclosed in curly braces ({}) that are executed repeatedly.
  4. Update Expression: An expression (e.g., $i++$, $i = i + 2$) that modifies the loop control variable. This is crucial; without it, the condition might never become false, leading to an infinite loop.

Comparison to 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.

Program to Demonstrate while Loop (With Dry Run)

The following program demonstrates the use of a while loop to print numbers from 1 to 5.