Skip to content
Java control flow 6 min read

while Loop

When you need to repeat a block of code but you don’t know in advance how many times it should run, the while loop is the right tool. It keeps going as long as a condition remains true, making it perfect for reading input, waiting on a resource, or processing data until a sentinel value appears.

Basic Syntax

while (condition) {
    // body — runs as long as condition is true
}
  • condition — a boolean expression evaluated before every iteration
  • body — executes only when the condition is true; skipped entirely if it starts false

A straightforward countdown:

int count = 1;
while (count <= 5) {
    System.out.println("Count: " + count);
    count++;
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

You are responsible for updating count inside the body. Forget that and you get an infinite loop — a common beginner mistake.

How Execution Flows

Picture these steps on every pass:

  1. Evaluate condition — if false, exit the loop immediately
  2. Execute body
  3. Go back to step 1

Because the condition is tested before the body, a while loop is called a pre-condition (or entry-controlled) loop. The body can run zero times if the condition is false from the very start.

int x = 10;
while (x < 5) {
    System.out.println("This never prints.");
}
System.out.println("Loop skipped entirely.");

Output:

Loop skipped entirely.

Tip: If you need the body to run at least once regardless of the condition, use a do-while loop instead.

Reading Input Until a Sentinel Value

One of the most natural uses for while is reading input until the user signals they are done:

import java.util.Scanner;

public class SumInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        int number;

        System.out.println("Enter numbers (0 to stop):");
        number = scanner.nextInt();

        while (number != 0) {
            sum += number;
            number = scanner.nextInt();
        }

        System.out.println("Total: " + sum);
    }
}

You can’t use a for loop here because you simply don’t know how many numbers the user will enter.

Iterating With an Unknown Bound

while shines whenever the exit condition depends on something calculated inside the loop:

// Find the first power of 2 greater than 1000
int power = 1;
while (power <= 1000) {
    power *= 2;
}
System.out.println("First power of 2 > 1000: " + power);

Output:

First power of 2 > 1000: 1024

Infinite Loops

Omit a meaningful condition (or use true) and the loop runs forever. This is intentional in server loops and event-processing systems:

while (true) {
    // process events, check flags, etc.
    if (shouldStop()) break;
}

Warning: Always make sure there is a reachable exit path (break, return, or throwing an exception) inside an infinite while (true) loop, or your program will hang and consume CPU indefinitely.

Using break and continue

  • break exits the loop immediately, regardless of the condition.
  • continue skips the rest of the current iteration and jumps back to the condition check.
int i = 0;
while (i < 10) {
    i++;
    if (i % 2 == 0) continue; // skip even numbers
    if (i == 7) break;         // stop before 7
    System.out.print(i + " ");
}

Output:

1 3 5 

Note: After continue, execution jumps directly back to the while condition — not to any update expression (there isn’t one). Make sure your loop variable is still updated correctly before calling continue, or you will create an accidental infinite loop.

Nested while Loops

You can nest while loops just like for loops. A classic example — printing a simple multiplication table:

int row = 1;
while (row <= 3) {
    int col = 1;
    while (col <= 3) {
        System.out.printf("%4d", row * col);
        col++;
    }
    System.out.println();
    row++;
}

Output:

   1   2   3
   2   4   6
   3   6   9

Warning: Just like nested for loops, deeply nested while loops can be O(n²) or worse. Keep nesting shallow and consider refactoring inner loops into separate methods.

while vs for — When to Use Which

SituationPreferred Loop
Known number of iterations (e.g., 1 to 10)for
Iterating over an array or collection by indexfor
Condition depends on runtime data or inputwhile
Body must run at least oncedo-while
Event loop / server loopwhile (true)

Both for and while are pre-condition loops and can technically replace each other — but choosing the right one makes your intent clearer to readers. See Control Statements for a broader overview.

Common Mistakes

MistakeProblemFix
Forgetting to update the loop variableInfinite loopAlways modify whatever the condition depends on inside the body
Updating before continue is unreachableInfinite loop on certain iterationsPlace the update before any continue statement
while (x = 5) instead of while (x == 5)Compile error — assignment returns int, not booleanUse == for comparison
Testing floating-point equality (while (x != 1.0))May loop forever due to roundingUse a threshold: while (Math.abs(x - 1.0) > 1e-9)

Under the Hood

Bytecode Translation

The Java compiler translates a while loop into a jump-based structure in bytecode. The pseudocode looks like:

LABEL_start:
  evaluate CONDITION → boolean
  if false → GOTO LABEL_end
  BODY
  GOTO LABEL_start
LABEL_end:

There is no dedicated “while loop” JVM instruction — just conditional and unconditional goto operations. This is identical to how the compiler handles a for loop with the initialization and update removed. The difference between for and while is purely a source-level syntactic choice; the resulting bytecode is the same.

You can verify this yourself with the javap -c tool, which disassembles .class files into bytecode instructions.

JIT Optimizations

Once the JVM’s Just-in-Time compiler (JIT) identifies a while loop as “hot” (executed many times), it applies the same optimizations it uses for for loops:

  • Loop unrolling — the body is duplicated 2–8 times per generated machine-code pass, reducing branch overhead.
  • Loop-invariant code motion — computations that produce the same result every iteration are hoisted out of the loop automatically.
  • Branch prediction — the CPU’s branch predictor learns the typical outcome of the condition check, allowing speculative execution of the body before the check even completes.

For tight numerical loops, the compiled machine code can be nearly as fast as equivalent C code.

Stack Memory

The while loop does not create a new stack frame on each iteration. All local variables declared before or inside the loop live in the same method stack frame as slots in the local variable table. Looping thousands of times does not grow the stack — it just overwrites those slots repeatedly.

Note: Be careful with variables declared inside the loop body — they are re-initialized on every iteration and do not persist across passes unless you declare them outside the loop.

Last updated June 13, 2026
Was this helpful?