Topic 38 of 119 4. Control Flow in Java Interactive Tutorial

Java while Loop: Condition-Driven Repetition With Examples

11 mins read Last updated: 22 Aug 2026 21,574 views

Direct Answer & Core Concept

A while loop repeats a block of code for as long as a condition stays true. It is the loop you reach for when you do not know in advance how many times you need to repeat, which is the one decision that separates it from a for loop. The execution order is simple. The condition is tested before every single iteration. If it is true, the body runs. Then the condition is tested again. It repeats exactly like that until the condition becomes false, and that is the moment the loop ends. Two consequences follow, and both catch beginners out. First, because the condition is tested first, a while loop may run zero times. If the condition is already false when the program reaches the loop, the body never executes at all. Second, and more seriously, the loop only stops if you change something. A for loop keeps its step in the header where you cannot forget it, but a while loop puts the condition at the top and the change inside the body, often many lines apart. Forget the change and the program hangs forever with no error message. That single rule, that something inside the body must move the condition toward false, is the thing to take away from this page.

Detailed Explanation & Mechanics

1) The Basic Syntax

Main.java
Run Online
while (condition) {
    // the body
}

There is no step expression and no counter in the header. Everything that makes the loop eventually finish has to live inside the body, which is exactly why a while loop is flexible and exactly why it is easy to break.

Main.java
Run Online
final int START_AT = 5;
int countdown = START_AT;
while (countdown > START_AT) {
    System.out.println("T-minus " + countdown);
    countdown = countdown - 1;
}System.out.println("Blast off!");

Read it as a sentence: while the countdown is greater than zero, print it and take one off. The line that takes one off is the only reason the loop ends.


Flow diagram showing while loop execution where the condition is tested first, the body runs only if true, and the change inside the body makes the condition eventually false
The condition is tested first, so a while loop can run zero times.

2) Execution Order, and the Zero-Iteration Case

  1. The condition is evaluated. This happens before the body, every single time.
  2. If it is false, the loop ends immediately. The body never runs, not even once.
  3. If it is true, the body runs from top to bottom.
  4. Control goes back to step 1. The condition is evaluated again from scratch.

Step 2 is the detail people forget, and it is the reason a while loop is an entry-controlled loop, also called a pre-test loop. If the condition is false when you arrive, the whole loop is skipped.

Main.java
Run Online
final int ALREADY_DONE = 0;
final int MAX_TRIES = 3;
int attempts = ALREADY_DONE;
while (attempts < MAX_TRIES) {
    System.out.println("This never prints");
    attempts++;
}System.out.println("Loop finished, body ran zero times");

That is a completely legal and correct program. If you need the body to run at least once no matter what, that is what a do-while loop is for.

3) The Termination Guarantee

The single most important rule: something inside the body must move the condition toward false. If nothing changes it, the loop runs forever and the program hangs with no error message at all.


Diagram contrasting a while loop missing its decrement line causing an infinite hang with the corrected version that decrements the counter
Forget the update and the condition stays true forever. The program hangs.

This is worth dwelling on because a while loop is structurally more dangerous than a for loop. A for loop keeps its counter, its bound and its step together in the header, so the step is impossible to miss. In a while loop the condition is at the top and the change is somewhere in the body, and the two can be twenty lines apart.

There is a second trap in the same family. If the change only happens on some paths through the body, the loop can still hang. A continue that skips the update, or an if that bypasses it, both reintroduce the infinite loop.

Main.java
Run Online
final int LIMIT = 5;
final int SKIP = 2;
int i = 0;
while (i < LIMIT) {
    i++;
    if (i == SKIP) {
        continue;
        // fine here, i was already incremented
    } System.out.println(i);
}

Notice the order there. The increment happens before the continue, so no iteration is ever wasted and the loop still terminates. Move the increment to the bottom and that continue becomes an infinite loop.

4) Counting Down and Counting Up With a while Loop

A while loop is not limited to counting down, it is simply less convenient for counting than a for loop, because you must declare and update the counter yourself.

Main.java
Run Online
final int HIGHEST = 5;
final int LOWEST = 1;
// counting down
int down = HIGHEST;
while (down >= LOWEST) {
    System.out.print(down + " ");
    down--;
}System.out.println();
// counting up
int up = LOWEST;
while (up <= HIGHEST) {
    System.out.print(up + " ");
    up++;
}System.out.println();

If you notice yourself writing exactly this, stop and use a for loop instead. The for loop version is shorter, harder to get wrong, and states the intent in one line. A while loop earns its place when the condition is not a simple range.

5) When a while Loop Is the Right Choice

SituationWhy while Fits
Reading until end of fileYou do not know the number of lines in advance.
Retrying an operationYou loop until it succeeds, however many tries that takes.
Waiting for a state to changePolling a queue, a flag or a database column.
Processing a streamYou consume items as they arrive, with no known total.
A simple countdownWorks, but a for loop is clearer. Prefer for.

The first four are genuine wins. Here is a realistic one, retrying a connection until it works.

Main.java
Run Online
final int MAX_ATTEMPTS = 5;
final int WAIT_MILLIS = 500;
int attempt = 0;
boolean connected = false;
while (!connected && attempt < MAX_ATTEMPTS) {
    attempt++;
    System.out.println("Attempt " + attempt + " of " + MAX_ATTEMPTS);
    connected = tryConnect();
    if (!connected) {
        System.out.println("Failed, waiting before retrying");
    }
}if (connected) {
    System.out.println("Connected on attempt " + attempt);
} else {
    System.out.println("Gave up after " + attempt + " attempts");
}

Notice the condition is a combination of two things, !connected && attempt < MAX_ATTEMPTS. That is very common and very readable: keep trying, but never more than the cap. The cap is what stops this being an infinite loop even if tryConnect() never succeeds.

6) The do-while Difference in One Comparison

Questionwhiledo...while
When is the condition tested?Before the bodyAfter the body
Can the body run zero times?YesNo, always at least once
Also calledEntry-controlledExit-controlled
Typical useRetry, poll, read until doneMenu prompt, validate input once
Ends withBrace onlyBrace plus a semicolon

The last row trips people up because it is the only place in Java where a loop needs a trailing semicolon. If you see a compile error pointing at the brace of a do-while, that is almost always why.


Two flow diagrams comparing while which tests the condition first and may run zero times against do while which always runs the body once before testing
A while loop may run zero times. A do-while always runs once.

7) Common Mistakes

MistakeSymptomFix
No update inside the bodyThe program hangs with no output.Add the line that moves the condition toward false.
Update only on some pathsWorks sometimes, hangs other times.Move the update to the top of the body, before any continue.
= instead of ==Always true, so an infinite loop.Use == to compare and = only to assign.
Condition false at the startThe body silently never runs.Use a do-while if you need one guaranteed pass.
Counting with a while loopCorrect, but longer than needed.Use a for loop when you are simply counting.
No cap on a retry loopRuns until something external changes.Add a maximum attempt count to the condition.


Infographic of six common while loop mistakes each shown with the wrong and the corrected code
Six while loop bugs. The first two produce a silent hang.

That sixth row is the one experienced developers still get caught by. A retry loop with no maximum will happily run all night, which is a real operational problem rather than a teaching example.

8) A Complete Example

Here is a full program showing a countdown, a retry with a cap, and a sentinel-controlled loop, which is the traditional way to read a list of numbers from a user.

Main.java
Run Online
final int SECRET = 7;
final int SENTINEL = -1;
final int MAX_GUESSES = 5;
int guess = 0;
int tries = 0;
while (guess != SECRET && tries < MAX_GUESSES) {
    tries++;
    guess = readGuess();
    if (guess == SENTINEL) {
        System.out.println("Giving up");
        break;
    } if (guess == SECRET) {
        System.out.println("Correct in " + tries + " tries");
    } else {
        System.out.println("Wrong, try again");
    }
}

A sentinel-controlled loop is worth knowing even though modern Java rarely uses it. The idea is that a special impossible value, here -1, means stop. The user enters numbers until they type the sentinel. It is a classic exam topic and a reasonable way to read an unknown number of values.

For escaping a running loop outright, see the break statement page. For the overview of all four loops and when to pick each, see the looping overview page.

Frequently Asked Questions

What is an entry-controlled loop?


A loop that tests its condition before running the body, so the body may run zero times. Both the for loop and the while loop are entry-controlled. A do-while loop is the opposite, called exit-controlled, and always runs at least once.

How do I prevent an infinite while loop?


Guarantee that something inside the body changes the condition toward false, and do it before any continue that might skip it. If your program appears to hang, the condition and its update are the first two places to look.

When should I use while instead of for?


Use while when you do not know the iteration count, such as reading until end of file, retrying an operation or waiting for a state change. Use for when you are counting, since it keeps the counter, bound and step together in the header.

Why does my while loop never run?


Because the condition was already false on the first test. This is correct behaviour, not a bug. If you need the body to run at least once, use a do-while loop.

Can a while loop have a counter like a for loop?


Yes, but you must declare the counter before the loop and update it inside the body yourself. If that is all you are doing, a for loop is shorter and safer.

Is a while loop slower than a for loop?


No, they compile to effectively the same code. Choose based on clarity rather than speed. A for loop communicates counting better, a while loop communicates repeating until something changes.

What is a sentinel-controlled loop?


A loop that ends when the input matches a special value, usually one that could not be valid data, such as minus one. It is how you read an unknown number of values. Modern Java tends to prefer collections or a stream instead.

Runnable Code Example: Java while Loop

Java 17+
Main.java
Run Online
// Demonstrates the Java while loop.
public class WhileLoopDemo {
    // Stand-ins for real input, so this file needs no imports
    // and runs in any online compiler.
    static int readGuess() {
        return 7;
        // pretend the user typed 7
    } static boolean tryConnect() {
        return true;
        // pretend the connection succeeds
    } public static void main(String[] args) {
        final int START_AT = 5;
        final int HIGHEST = 5;
        final int LOWEST = 1;
        final int LIMIT = 5;
        final int SECRET = 7;
        final int SENTINEL = -1;
        final int MAX_GUESSES = 5;
        final int MAX_ATTEMPTS = 3;
        // 1) THE CLASSIC COUNTDOWN
        //    The decrement inside the body is the ONLY reason this stops.
        System.out.print("countdown: ");
        int countdown = START_AT;
        while (countdown > 0) {
            System.out.print(countdown + " ");
            countdown = countdown - 1;
        } System.out.println("Blast off!");
        // 2) COUNTING UP AND DOWN WITH while
        //    Legal, but a for loop is shorter for this. Shown for contrast.
        System.out.print("up:   ");
        int up = LOWEST;
        while (up <= HIGHEST) {
            System.out.print(up + " ");
            up++;
        } System.out.println();
        // 3) ZERO ITERATIONS
        //    The condition is tested FIRST and it is already false,
        //    so the body never runs at all.
        final int ALREADY_DONE = 0;
        int neverRuns = 0;
        int alreadyFinished = ALREADY_DONE;
        while (alreadyFinished < LIMIT) {
            neverRuns++;
            alreadyFinished++;
        } System.out.println("zero-iteration loop ran the body " + neverRuns + " times");
        // 4) RETRY WITH A CAP
        //    The attempt limit is what stops this being an infinite loop,
        //    even if the connection never succeeds.
        int attempt = 0;
        boolean connected = false;
        while (!connected && attempt < MAX_ATTEMPTS) {
            attempt++;
            connected = tryConnect();
            System.out.println("attempt " + attempt + " connected=" + connected);
        } System.out.println(connected ? "Connected" : "Gave up");
        // 5) SENTINEL-CONTROLLED LOOP
        //    The user types values until they enter the sentinel, -1.
        int guess = 0;
        int tries = 0;
        while (guess != SECRET && tries < MAX_GUESSES) {
            tries++;
            guess = readGuess();
            if (guess == SENTINEL) {
                System.out.println("Sentinel entered, stopping");
                break;
            } if (guess == SECRET) {
                System.out.println("Correct in " + tries + " tries");
            } else {
                System.out.println("Wrong, try again");
            }
        } // 6) continue IS SAFE HERE, because the increment happens FIRST.
        //    Move the increment below the continue and it becomes infinite.
        System.out.print("skipping 2: ");
        int i = 0;
        while (i < LIMIT) {
            i++;
            if (i == SKIP) {
                continue;
            } System.out.print(i + " ");
        } System.out.println();
        // 7) THE INFINITE LOOP, left commented so it does not hang.
        //    There is no decrement, so the condition never becomes false.
        // int stuck = 5;
        // while (stuck > 0) {
        //     System.out.println("this never ends");
        //     // forgot stuck-- here
        // }
    }
}/*
    ACTUAL OUTPUT:

        countdown: 5 4 3 2 1 Blast off!
        up:   1 2 3 4 5
        zero-iteration loop ran the body 0 times
        attempt 1 connected=true
        Connected
        Correct in 1 tries
        skipping 2: 1 3 4 5

    THE THREE THINGS TO REMEMBER
    1) The condition is tested BEFORE the body, so a while loop may
       run ZERO times. Use a do-while if you need one guaranteed pass.
    2) Something inside the body must move the condition toward false.
       That is the termination guarantee, and without it the loop hangs.
    3) Update the state at the TOP of the body, before any continue,
       so no path can skip the update and restart the loop forever.
*/

Common Java Technical Interview Questions & Answers

Interview Prep
Q1: What is an entry-controlled loop?\nA1: A loop that tests its condition before running the body, so the body may run zero times. Both the for loop and the while loop are entry-controlled, while a do-while loop is exit-controlled and always runs at least once.\nQ2: How do you prevent an infinite while loop?\nA2: Ensure that whatever the condition tests is changed inside the body so the condition moves toward false. Place that update at the top of the body, before any continue or early exit that could skip it, and add a maximum attempt count when the loop is a retry.\nQ3: When is a while loop better than a for loop?\nA3: When the iteration count is genuinely unknown, such as reading until end of file, retrying an operation until it succeeds, or waiting for a state change. A for loop is better when you are counting, because it keeps the counter, bound and step together in the header.\nQ4: Why would a while loop body never execute?\nA4: Because the condition was already false on the very first test, which is correct behaviour for an entry-controlled loop. If the body must run at least once regardless, use a do-while loop instead.\nQ5: Can a while loop contain a counter?\nA5: Yes, but you must declare it before the loop and increment it inside the body. If counting is all the loop does, a for loop is shorter and removes the chance of forgetting the update.\nQ6: Is a while loop slower than a for loop?\nA6: No, they compile to effectively identical code. Choose whichever reads more clearly: a for loop communicates counting, a while loop communicates repeating until a condition changes.\nQ7: What is a sentinel-controlled loop and when is it used?\nA7: A loop that ends when the input equals a special value that could not be valid data, such as minus one. It is the traditional way to read an unknown number of values, though modern Java usually prefers a collection or a stream.\nQ8: What happens if the update in a while loop is skipped by a continue?\nA8: The condition never changes on that path, so the loop can run indefinitely. This is why the update belongs at the top of the body, before any continue statement.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

1) Always make the update that moves the condition toward false the first statement in the body, so no branch or continue statement can skip it and turn the loop into an infinite one.\n2) Choose a for loop when you are simply counting, because it keeps the counter, the bound and the step in one visible header, and use a while loop only when the condition is not a simple range.\n3) Use a do-while loop instead of a while loop whenever the body must run at least once, such as displaying a menu or reading the first input value, and remember the do-while needs a trailing semicolon.\n4) Put a maximum attempt count in the condition of any retry or polling loop, so a persistent external failure cannot leave it running indefinitely.\n5) Check the condition and its update first whenever a program appears to hang, since a missing or wrongly ordered update is by far the most common cause.\n6) Prefer a positive condition such as while (!done) over a negated one such as while (done == false), because the positive form reads more naturally and is less easy to invert by mistake.\n7) Combine conditions with && to cap a loop, as in while (!connected && attempt < MAX), so the loop stops for either reason rather than relying on a break.\n8) Declare the loop state variable immediately before the loop rather than at the top of the method, so the relationship between the variable and the condition is obvious.\n9) Use break sparingly, since escaping a loop with a break usually hides a condition that could have been written more clearly, and prefer expressing the exit in the condition itself.\n10) Do not use a while loop to walk a collection, because the for-each loop cannot have an off-by-one error and reads better, and reserve while for repeating until a condition changes.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.