while Loop in Java – Syntax and Examples
The while loop repeats a block of code as long as a condition stays true. Unlike the for loop, which is built around counting, while is perfect when you do not know in advance how many repetitions you need: read input until the user types 0, retry until a call succeeds, or process items until a queue is empty.
This tutorial explains the syntax and flow of the while loop, shows typical patterns with runnable examples, and covers infinite loops and common mistakes.
1. Syntax and Flow
while (condition) {
// body: runs while condition is true
// something here must eventually make the condition false
}
- Evaluate the condition.
- If it is
false, skip the loop and continue after it. - If it is
true, run the body, then go back to step 1.
Because the condition is checked first, the body may run zero times. That makes while an entry-controlled loop.
2. Basic Examples
public class WhileBasics {
public static void main(String[] args) {
int count = 5;
while (count > 0) { // checked before every iteration
System.out.print(count + " ");
count--; // move toward the end condition
}
System.out.println("liftoff!");
int number = 90817, reversed = 0;
while (number > 0) {
reversed = reversed * 10 + number % 10;
number /= 10;
}
System.out.println("Reversed digits: " + reversed);
}
}
5 4 3 2 1 liftoff! Reversed digits: 71809
In both loops, the body changes the variable used in the condition (count--, number /= 10). Without that, the condition would never become false.
3. Loops with an Unknown Number of Iterations
Here we do not know how many times the loop will run; it simply continues until a goal is reached:
public class UnknownIterations {
public static void main(String[] args) {
// How many years until savings double at 8% a year?
double savings = 10_000, target = 20_000;
int years = 0;
while (savings < target) {
savings *= 1.08;
years++;
}
System.out.printf("Doubled after %d years (Rs. %.2f)%n", years, savings);
// Collatz sequence: steps until n reaches 1
int n = 27, steps = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
System.out.println("Collatz steps for 27: " + steps);
}
}
Doubled after 10 years (Rs. 21589.25) Collatz steps for 27: 111
4. Reading Input Until a Sentinel Value
A sentinel is a special value that means "stop". This program adds numbers until it reads 0. The sample input is 15 40 7 38 0:
import java.util.Scanner;
public class SumUntilZero {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int total = 0, count = 0;
int value = in.nextInt();
while (value != 0) { // 0 means "stop"
total += value;
count++;
value = in.nextInt();
}
System.out.println("Read " + count + " numbers, total = " + total);
}
}
Read 4 numbers, total = 100
Note the pattern: read the first value before the loop, and read the next value at the end of the body. The condition is then always checked against a fresh value.
5. Iterators and while (true)
The while loop is the natural partner of an Iterator, and while (true) with break is useful when the exit decision happens in the middle of the body:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class WhileWithIterator {
public static void main(String[] args) {
List<String> emails = new ArrayList<>(List.of("a@x.com", "invalid", "b@y.com", "nope"));
Iterator<String> it = emails.iterator();
while (it.hasNext()) { // the classic iterator loop
String e = it.next();
if (!e.contains("@")) it.remove();
}
System.out.println("Valid emails: " + emails);
// while (true) with break: useful when the exit is in the middle
int attempt = 0;
while (true) {
attempt++;
boolean success = attempt == 3; // pretend the third try works
System.out.println("attempt " + attempt + (success ? ": success" : ": failed"));
if (success) break;
}
}
}
Valid emails: [a@x.com, b@y.com] attempt 1: failed attempt 2: failed attempt 3: success
Servers, game loops and message consumers often run in while (true) or while (running) loops that end only when the program shuts down.
6. while vs for vs do-while
| Loop | Condition checked | Minimum runs | Best for |
|---|---|---|---|
while | Before each iteration | 0 | Unknown number of repetitions |
for | Before each iteration | 0 | Counting and index-based loops |
do-while | After each iteration | 1 | Bodies that must run at least once |
Any for loop can be rewritten as a while loop and vice versa; choose the one that makes the intent clearest.
7. Common Mistakes
- Forgetting to update the condition variable, which creates an infinite loop.
- A semicolon after the condition:
while (x < 10);loops forever on an empty body ifxis below 10. - Off-by-one conditions such as
<=instead of<. - Comparing floating-point values for exact equality in the condition, which may never become true.
- Busy-waiting with
while (!ready) { }in multithreaded code, which wastes CPU; use proper synchronization tools instead.
8. Summary
- A
whileloop runs its body as long as its condition is true, checking the condition first. - The body may run zero times.
- It is ideal when the number of iterations is not known in advance.
- Something in the body must change the condition, or the loop never ends.
while (true)withbreakhandles exits in the middle of the body.
Related Tutorials
Reference: Oracle Java Tutorials: The while and do-while Statements