while Loop

A while loop tests its condition before each iteration, so its body might run many times, exactly once, or not at all — it is the right tool when you don't know the iteration count in advance.

A while loop repeats a block of statements for as long as a boolean condition holds, checking that condition before every iteration. It is the simplest looping construct in Java and the natural choice whenever the number of repetitions depends on something discovered while the loop runs, rather than being known up front.

What Is a while Loop

The syntax is while (condition) { body }. Before each pass through the body, Java evaluates condition; if it is true, the body runs and the check repeats, and if it is false, the loop ends and execution continues after it.

int count = 0;
while (count < 3) {
    System.out.println("count = " + count);
    count++;
}
System.out.println("done");
// count = 0
// count = 1
// count = 2
// done

Pre-Test Loop: Condition Checked First

while is a pre-test (entry-controlled) loop: the condition is evaluated before the body runs, every single time, including the very first time. This means the body is never guaranteed to execute at all — if the condition is false from the start, the loop body is skipped entirely.

This is the key structural difference from do-while, which checks the condition after the body and therefore always runs the body at least once.

Zero Iterations Is Normal

A while loop that never runs its body isn't a bug by itself — it's a direct, expected consequence of the condition starting out false. This commonly happens with empty collections, already-satisfied stopping conditions, or defensive checks.

int[] items = {};
int i = 0;
while (i < items.length) { // items.length is 0, so this is false immediately
    System.out.println(items[i]);
    i++;
}
System.out.println("processed " + i + " items"); // processed 0 items

Conditions: What Belongs in a while Header

The condition must be an expression of type boolean (or Boolean, which is unboxed automatically). It typically compares a counter, checks a flag, inspects an object's state (like scanner.hasNextInt()), or combines several checks with && / ||.

Unlike some other languages, Java does not allow an int or other non-boolean type directly as a while condition — while (1) does not compile. Use while (true) for an intentionally unconditional loop.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
int sum = 0;
while (scanner.hasNextInt()) {
    sum += scanner.nextInt();
}
System.out.println("Sum: " + sum);

Loop Progress: Something Must Change

For a while loop to terminate, something the condition depends on must change inside the body, eventually making the condition false. Forgetting this update is the single most common cause of an infinite loop.

int n = 10;
while (n > 0) {
    System.out.println(n);
    n--; // without this line, the condition n > 0 would never become false
}

Intentional Infinite Loops

while (true) { } is idiomatic Java for a loop meant to run until something inside it explicitly stops it — typically with break, return, or by throwing an exception. This pattern is common in servers, event loops, and menu-driven programs.

Scanner scanner = new Scanner(System.in);
while (true) {
    System.out.print("Enter a command (or 'quit'): ");
    String command = scanner.nextLine();
    if (command.equals("quit")) {
        break;
    }
    System.out.println("You entered: " + command);
}

Nested while Loops

Like for, while loops can be nested. Each variable driving an inner loop's condition must be reset appropriately before the inner loop starts each time, since while does not have a built-in initialization clause the way for does.

int i = 0;
while (i < 3) {
    int j = 0; // reset for every outer iteration
    while (j < 2) {
        System.out.println(i + "," + j);
        j++;
    }
    i++;
}

while vs for: Choosing the Right Tool

for and while are interchangeable in the sense that any for loop can be rewritten as a while loop and vice versa — for is really syntactic sugar that groups init/condition/update together. Choose based on readability: use for when there's a natural counter with a clear start, stop, and step; use while when the stopping condition isn't a simple counter (waiting for input, searching until found, retrying until success).

// Equivalent to: for (int i = 0; i < 5; i++) { ... }
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

Practical Usage

Common while patterns: reading input until a sentinel, retry loops with a give-up limit, searching a data structure until a match is found, and processing until some external condition changes.

// Search until found or list exhausted
int index = 0;
boolean found = false;
while (index < names.length && !found) {
    if (names[index].equals(target)) {
        found = true;
    } else {
        index++;
    }
}

Edge Cases

A while loop's condition can reference variables that change through method calls with side effects, not just simple counters — for example while (iterator.hasNext()). Be careful that such calls genuinely progress toward termination; calling a method that doesn't change relevant state will loop forever just as surely as forgetting i++.

Floating-point conditions (while (x < 1.0)) can behave surprisingly due to rounding — an accumulated step might never exactly reach the target, or might overshoot it, changing the iteration count from what you'd expect with exact arithmetic.

Complete Example

The number of steps to reach 1 in the Collatz sequence isn't known in advance, making while a much more natural fit here than a counted for loop.

public class CollatzSteps {
    public static void main(String[] args) {
        long n = 27;
        int steps = 0;
        while (n != 1) {
            if (n % 2 == 0) {
                n = n / 2;
            } else {
                n = 3 * n + 1;
            }
            steps++;
        }
        System.out.println("Reached 1 in " + steps + " steps");
    }
}

Mental Model

Picture a while loop as a guard standing at the top of the body: before letting execution in, it checks the condition. True means enter and run the body once more, then come back and ask again. False means turn execution away entirely, whether that's on the very first ask or the hundredth.

Quick Reference

while (condition) { body }

condition checked BEFORE each iteration, including the first
body      may run zero or more times
while (true) { }   intentional infinite loop, typically exited via break

Must ensure: something the condition depends on changes inside the body,
or the loop never terminates.

Key Takeaways

while checks its condition before every iteration, so the body can run zero times.

The loop only terminates if something the condition depends on changes inside the body.

while (true) with an internal break is the idiomatic way to write an intentional infinite loop.

Prefer while over for when the stopping condition isn't a simple counted range.

Any for loop can be rewritten as a while loop, and vice versa — the choice is about readability, not capability.

int i = 0; while (i < 5); { System.out.println(i); i++; } int i = 0; while (i < 5) { System.out.println(i); i++; }

A stray semicolon after the while header creates an empty infinite loop body (the condition never changes), and the block that follows just runs once, unrelated to the loop.

int n = 5; while (n > 0) { System.out.println(n); // forgot to change n } int n = 5; while (n > 0) { System.out.println(n); n--; }

Without updating n inside the body, the condition n > 0 never becomes false, producing an infinite loop.

while (1) { //... } while (true) { //... } Unlike C, Java does not treat integers as truthy/falsy in a boolean context — the condition must be an actual boolean expression, so while(1) is a compile error.

double x = 0.0; while (x != 1.0) { x += 0.1; } double x = 0.0; while (x < 1.0 - 1e-9) { x += 0.1; }

Comparing floating-point values with != (or ==) is unreliable because of rounding error — x may skip past 1.0 without ever equaling it exactly, causing an infinite loop; comparing with a tolerance or using < avoids the trap.

What is the key structural difference between while and do-while?

while checks its condition before running the body (so the body can execute zero times); do-while checks its condition after running the body (so the body always executes at least once).

If a while loop's condition is false the very first time it is checked, how many times does the body run?

Zero times — the loop is skipped entirely and execution continues immediately after it.

What must be true inside a while loop's body for the loop to eventually terminate?

Something the condition depends on must change over the course of iterations so that the condition eventually evaluates to false; otherwise the loop runs forever.

Why doesn't while (1) { } compile in Java, unlike some C-family languages?

Java requires the while condition to be an actual boolean expression — it does not implicitly convert numeric types to boolean, so an int like 1 cannot be used as a truthy value there.

When would you prefer while over for?

When the number of iterations isn't known ahead of time and isn't driven by a simple counter — for example, reading input until a sentinel appears, retrying until success, or searching until a match is found.

What is the idiomatic way to write an intentional infinite loop in Java, and how is it normally exited?

while (true) { ... }, exited from inside the body using break, return, or by throwing an exception.

Why can comparing a floating-point loop variable with != or == be risky as a while condition?

Floating-point arithmetic accumulates rounding error, so a value that mathematically should equal a target may never exactly reach it (or may skip past it), making an equality-based stopping condition unreliable and potentially causing an infinite loop.

Write a while loop that prints the powers of 2 (starting at 1) that are less than 1000.

int power = 1; while (power < 1000) { System.out.println(power); power *= 2; }

Starting at 1 and doubling each time naturally generates 1, 2, 4, 8, ... and the loop stops as soon as the value reaches or exceeds 1000.

What does this print, and why?

4 — x goes 10 -> 5 -> 2 -> 1 (integer division truncates), and the loop runs once for each of those three divisions... tracing carefully: 10>1 (x=5,count=1), 5>1 (x=2,count=2), 2>1 (x=1,count=3), 1>1 is false, loop stops. So the actual output is 3.

Write a while loop that reads integers from a Scanner until the user enters -1, and prints their sum (not including -1).

Scanner scanner = new Scanner(System.in); int sum = 0; int value = scanner.nextInt(); while (value != -1) { sum += value; value = scanner.nextInt(); } System.out.println(sum);

The value is read once before the loop starts (so the condition has something to check), then re-read at the end of each iteration; as soon as -1 is entered, the condition becomes false and the loop exits without adding -1 to the sum.

What does this print (trace it through)?

0 1 2 8 9 — for i = 0,1,2 it prints normally and increments; when i becomes 3, the body jumps it to 8 before printing, so 8 is printed, then i becomes 9 on increment, prints 9, then increments to 10 and the loop condition (10 < 10) becomes false.

int x = 10;
int count = 0;
while (x > 1) {
    x = x / 2;
    count++;
}
System.out.println(count);
int i = 0;
while (i < 10) {
    if (i == 3) {
        i = 8;
    }
    System.out.print(i + " ");
    i++;
}