Java While Loop

Su Suriya Ravichandran Updated 14 Nov 2026
6 min read ·Lesson 19 of 133

A loop repeats a block of code. The while loop repeats it as long as a condition remains true, checking the condition before each repetition. It is the natural choice when the number of repetitions is not known in advance: read until the input ends, retry until a request succeeds, keep running until the user quits.

Syntax

while (condition) {
    // body: runs repeatedly while condition is true
}
int count = 1;

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

Output:

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

Step by step

  1. count starts at 1.
  2. The condition count <= 5 is checked. It is true, so the body runs: it prints and increments count to 2.
  3. Control returns to the condition. Steps 2–3 repeat for 2, 3, 4, and 5.
  4. After printing 5, count becomes 6. The condition 6 <= 5 is false, so the loop ends and execution continues with Done.

Every working while loop has three parts:

PartHerePurpose
Initializationint count = 1;Sets up the state the condition depends on
Conditioncount <= 5Decides whether to run the body again
Updatecount++Changes the state so the condition will eventually become false

Zero Iterations

The condition is checked before the first run. If it is false at the start, the body never executes:

int stock = 0;
while (stock > 0) {
    System.out.println("Selling one item");
    stock--;
}
// prints nothing

This is a feature: a while loop handles the empty case automatically, without a separate if.

Infinite Loops

If nothing in the body ever makes the condition false, the loop never ends:

int i = 1;
while (i <= 5) {
    System.out.println(i);
    // missing i++: prints 1 forever
}

Other common causes are updating the wrong variable, or updating in the wrong direction (i-- when the condition expects i to grow). If a program hangs or floods the console, check the update step first. Press Ctrl+C in the terminal to stop it.

A loop that is meant to run indefinitely is written while (true) and exits through break or return:

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.print("> ");
    String line = sc.nextLine().strip();
    if (line.equals("exit")) {
        break;
    }
    System.out.println("You typed: " + line);
}

This pattern fits when the exit decision is made in the middle of the body, after reading input, rather than at the top. Servers, game loops, and command shells are built this way.

Condition-Driven Loops

The strength of while is looping on a condition that is not a simple counter.

Repeating until a result is reached

int number = 1234;
int digits = 0;

while (number != 0) {
    number /= 10;
    digits++;
}
System.out.println(digits);   // 4

Each iteration removes the last digit by integer division. The loop runs as many times as there are digits, a number not known before starting. (For an input of 0 this returns 0, an edge case the caller should handle.)

Retrying with a limit

int attempts = 0;
boolean connected = false;

while (!connected && attempts < 3) {
    attempts++;
    System.out.println("Connecting, attempt " + attempts);
    connected = tryConnect();
}

if (!connected) {
    System.out.println("Giving up after " + attempts + " attempts");
}

Two conditions combine: stop on success or after three tries. Bounding a retry loop guarantees it ends even if the operation never succeeds.

Processing until input ends

Scanner sc = new Scanner(System.in);
double sum = 0;
int n = 0;

while (sc.hasNextDouble()) {
    sum += sc.nextDouble();
    n++;
}
if (n > 0) {
    System.out.printf("Average of %d values: %.2f%n", n, sum / n);
}

hasNextDouble() returns false when the input ends or the next token is not a number, so the loop processes exactly the values available.

The do-while Loop

A do-while loop checks its condition after the body, so the body always runs at least once:

do {
    // body
} while (condition);

Note the semicolon after the condition; it is required here.

int x = 10;

while (x < 5) {
    System.out.println("while: " + x);    // never runs
}

do {
    System.out.println("do-while: " + x); // runs once
} while (x < 5);

Output:

do-while: 10

The classic use is input that must be requested before it can be validated:

Scanner sc = new Scanner(System.in);
int choice;

do {
    System.out.print("Choose 1-3: ");
    choice = sc.nextInt();
} while (choice < 1 || choice > 3);

System.out.println("You chose " + choice);

The prompt must appear at least once, and repeats only if the answer is invalid. With a plain while, choice would need a dummy starting value to enter the loop.

whiledo-while
Condition checkedBefore each iterationAfter each iteration
Minimum iterations01
Typical useLoop may legitimately not run at allFirst pass is always needed (menus, prompts)

while Versus for

Any for loop can be written as a while loop, and the reverse. The difference is clarity:

// for: counter-based, all loop control in one line
for (int i = 0; i < 10; i++) { ... }

// while: same behavior, control spread across three places
int i = 0;
while (i < 10) {
    ...
    i++;
}

Use for when iterating a known range or collection. Use while when the loop depends on a condition that changes for reasons other than a simple counter. A while loop's counter variable also stays in scope after the loop, which is sometimes needed and sometimes a source of accidental reuse.

Practical Example: Number Guessing Game

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class GuessGame {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int secret = ThreadLocalRandom.current().nextInt(1, 101);
        int maxTries = 7;
        int tries = 0;
        boolean won = false;

        System.out.println("Guess a number between 1 and 100.");

        while (!won && tries < maxTries) {
            System.out.print("Guess #" + (tries + 1) + ": ");
            if (!sc.hasNextInt()) {
                System.out.println("Enter a whole number.");
                sc.next();               // discard invalid token
                continue;                // does not count as a try
            }
            int guess = sc.nextInt();
            tries++;

            if (guess == secret) {
                won = true;
            } else if (guess < secret) {
                System.out.println("Higher.");
            } else {
                System.out.println("Lower.");
            }
        }

        if (won) {
            System.out.println("Correct in " + tries + " tries!");
        } else {
            System.out.println("Out of tries. The number was " + secret + ".");
        }
    }
}

The loop condition !won && tries < maxTries captures both ways the game can end. Invalid input is discarded and continue jumps back to the condition without incrementing tries. Seven tries is enough to always win with a halving strategy, since 2⁷ = 128 > 100. After the loop, the program checks why it ended, which is a common need after a loop with more than one exit condition.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining
Ask about this post
AI Ask about this post

Ask questions about Java While Loop and get answers drawn from it.

Signed-in readers only.