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
Frequently Asked Questions (FAQ)
Q1. What is a while loop in Java?
A loop that repeats a block of code as long as its boolean condition is true. The condition is checked before every iteration.
Q2. When should I use a while loop?
When you do not know how many times the loop must run, such as reading input until a sentinel, retrying an operation, or processing items until none are left.
Q3. What is the difference between while and do-while?
while checks the condition before the body, so the body may not run at all. do-while checks after the body, so it always runs at least once.
Q4. What is the difference between while and for loops?
They are equally powerful. for groups initialization, condition and update in one header and suits counting. while has only a condition and suits loops driven by events or data.
Q5. How do I write an infinite while loop?
while (true) { ... }. Use break or return inside to end it when appropriate.
Q6. Why does my while loop never end?
The condition never becomes false: the variable it tests is not updated, is updated in the wrong direction, or there is a semicolon right after the condition.
Q7. Can a while loop run zero times?
Yes. If the condition is false at the start, the body is skipped entirely.
Q8. Can I use break and continue in a while loop?
Yes. break exits the loop; continue jumps back to the condition check. With continue, make sure the condition variable is still updated, or the loop may never end.
Q9. What is a sentinel-controlled loop?
A loop that runs until it reads a special "stop" value, such as 0, -1 or the word "quit".
Q10. What is a counter-controlled loop?
A loop that runs a fixed number of times using a counter variable. It can be written with while, but for is usually clearer.
Q11. Is while(true) bad practice?
Not when the exit point is naturally in the middle of the body or the loop should run for the program's lifetime. Make sure there is a clear way out, such as break, return or a flag.
Q12. Can the while condition contain multiple conditions?
Yes, combine them with && and ||: while (attempts < 3 && !connected).
Q13. Does a while loop need braces?
Not for a single statement, but always using braces avoids bugs when more statements are added.
Q14. How do I loop through a list with a while loop?
Use an iterator: Iterator<T> it = list.iterator(); while (it.hasNext()) { T x = it.next(); ... }. This also lets you remove elements safely with it.remove().
Q15. Can I declare a variable in the while condition?
No. Declare it before the loop. You can, however, assign inside the condition, as in while ((line = reader.readLine()) != null).
Q16. How do I stop a loop from another thread?
Loop on a volatile boolean running flag or check Thread.currentThread().isInterrupted(), and set the flag or interrupt the thread from outside.
Q17. Why is busy waiting with while a problem?
A loop like while (!done) { } keeps the CPU busy doing nothing. Use blocking tools such as CountDownLatch, BlockingQueue or wait()/notify() instead.
Q18. Can a while loop be nested?
Yes. A while loop can contain other loops of any kind, but deep nesting reduces readability; extract inner loops into methods when they grow.
Q19. What does while(false) do?
Its body would never run, so the Java compiler reports it as an "unreachable statement" error.
Q20. Is a while loop slower than a for loop?
No. Both compile to the same kind of bytecode. Choose based on readability, not speed.