Java while Loop: Syntax, Examples, break & continue

 // Syntax: while (condition) { // code block }
int i = 0;
while (i < 5) {
    System.out.println(i);
    i = i + 1;
}

Output:

0
1
2
3
4

Related: do-while loop (runs at least once) | for loop (counter-based) | if-else

1. Execution Rules & Condition Contract 🔝

Element Type / Timing Execution Rule
condition boolean (Pre-test) Checked before every iteration; if false initially, body runs 0 times.
break; Jump statement Immediately exits the while loop and resumes after the closing }.
continue; Jump statement Skips remaining lines in the current pass and jumps back to while (condition).

2. Boolean Flag Control & When Condition Is False 🔝

Instead of an integer counter, a while loop can test a boolean variable directly. If the condition starts false (such as x < 5 when x = 10), the loop body never executes—which is the core difference between while and do-while:

boolean my_condition = true;
while (my_condition) {
    System.out.println(my_condition);
    my_condition = false;  // Stops loop after first pass
}

 // Pre-test rule: When condition starts false (x = 10, x < 5), body executes 0 times!
int x = 10;
while (x < 5) {
    System.out.println("Never printed");
}
System.out.println("After false-start while loop, x is still: " + x);

Terminal Output:

true
After false-start while loop, x is still: 10

3. Exiting a while Loop Early with break 🔝

Break and continue in Java while loop

Placing a break; inside an if check stops the loop immediately when i == 2, so only 1 is printed:

int i = 0;
while (i < 5) {
    i = i + 1;
    if (i == 2) {
        break;  // Immediately exits the while loop when i reaches 2
    }
    System.out.println(i);
}

Terminal Output:

1

4. Skipping an Iteration with continue 🔝

Replacing break with continue skips System.out.println(2) when i == 2 and jumps straight to the top while (i < 5) check to print 3, 4, 5:

int i = 0;
while (i < 5) {
    i = i + 1;
    if (i == 2) {
        continue;  // Skips println(2) and jumps back to while (i < 5)
    }
    System.out.println(i);
}

Terminal Output:

1
3
4
5

5. Infinite Loops & Emergency Break Guards 🔝

If the loop variable moves away from the termination boundary (for example, decrementing i = i - 1 while testing i < 5), the condition never becomes false, creating an infinite loop unless stopped by a break:

 // Caution: Decrementing i (i = i - 1) keeps i < 5 forever -> infinite loop!
int i = 0;
while (i < 5) {
    System.out.println("Safety break at i = " + i);
    i = i - 1;
    if (i == -2) break;  // Emergency guard to stop runaway loop
}

Terminal Output:

Safety break at i = 0
Safety break at i = -1

6. Comparison: while vs do-while vs for Loop 🔝

Feature while (cond) do-while for (init; cond; step)
Condition Check Before each pass After each pass Before each pass
Min Iterations 0 1 (Guaranteed) 0
Target of continue Top while (cond) Bottom while (cond); Update step (i++)

7. Practical Recipe: Summing the Digits of a Number 🔝

When the number of digits is unknown ahead of time, while (n > 0) repeatedly extracts the last digit with n % 10 and strips it with n /= 10:

public class SumDigitsWhile {
    public static int sumOfDigits(int n) {
        int sum = 0;
        while (n > 0) {
            sum += (n % 10);  // Extract last digit
            n /= 10;          // Drop last digit
        }
        return sum;
    }
    public static void main(String[] args) {
        System.out.println("Digit sum of 4589: " + sumOfDigits(4589));
    }
}

Terminal Output:

Digit sum of 4589: 26

8. Production Recipe: Binary Search with while (low <= high) 🔝

while (low <= high) is the standard idiom for two-pointer algorithms like binary search on a sorted Java array:

public class BinarySearchWhile {
    public static int search(int[] sorted, int target) {
        int low = 0, high = sorted.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (sorted[mid] == target) return mid;
            if (sorted[mid] < target) low = mid + 1;
            else high = mid - 1;
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] data = {10, 20, 30, 40, 50};
        System.out.println("Index of 40: " + search(data, 40));
    }
}

Terminal Output:

Index of 40: 3

9. Common Developer Pitfalls & Traps 🔝

Infinite Loop When Placing continue Before i++

Unlike a for loop (where continue automatically runs i++), continue inside a while loop jumps directly to while (i < 5). If i = i + 1; is placed after if (i == 2) continue;, i remains stuck at 2 forever!

Stray Semicolon: while (i < 5); { ... }

Writing a semicolon right after while (i < 5); creates an empty body that spins forever if i < 5 is true, never reaching the curly braces below it.

10. Complete Compilable Java Program 🔝

public class WhileLoopFullDemo {
    public static void main(String[] args) {
        int i = 0, sum = 0;
        while (i < 5) {
            i++;
            if (i == 2) continue;  // Skips adding 2
            if (i == 5) break;     // Stops when i reaches 5
            sum += i;              // Adds 1 + 3 + 4 = 8
        }
        if (sum == 8 && i == 5) {
            System.out.println("Check 1 Passed: continue(2) and break(5) produced sum=8.");
        }
        int countdown = 3;
        while (countdown > 0) {
            countdown--;
        }
        if (countdown == 0) {
            System.out.println("Check 2 Passed: Countdown reached 0 cleanly.");
        }
        System.out.println("All Java while loop verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: continue(2) and break(5) produced sum=8.
Check 2 Passed: Countdown reached 0 cleanly.
All Java while loop verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

When should I use a while loop instead of a for loop?

Use while when you do not know how many iterations will occur ahead of time (for example, reading lines from a file, polling a queue, or advancing two converging pointers).

Does Java allow while (1) for an infinite loop?

No. Java requires a strict boolean expression, so you must write while (true).

Why does the Java compiler reject code after while (true) without a break?

Java's flow analyzer detects that while (true) without a break can never exit normally and flags any statement after the loop as a compile-time unreachable statement error.

How do I iterate over an ArrayList with a while loop?

Use an Iterator<E> it = list.iterator(); with while (it.hasNext()) { E item = it.next(); } (see ArrayList Tutorial).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer