Java While Loop
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
countstarts at 1.- The condition
count <= 5is checked. It istrue, so the body runs: it prints and incrementscountto 2. - Control returns to the condition. Steps 2–3 repeat for 2, 3, 4, and 5.
- After printing 5,
countbecomes 6. The condition6 <= 5isfalse, so the loop ends and execution continues withDone.
Every working while loop has three parts:
| Part | Here | Purpose |
|---|---|---|
| Initialization | int count = 1; | Sets up the state the condition depends on |
| Condition | count <= 5 | Decides whether to run the body again |
| Update | count++ | 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.
while | do-while | |
|---|---|---|
| Condition checked | Before each iteration | After each iteration |
| Minimum iterations | 0 | 1 |
| Typical use | Loop may legitimately not run at all | First 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.