Java While Loop
Loops repeat a block of code. The while loop is the simplest: it keeps running as long as its condition is true. Use it when you don't know in advance how many repetitions you'll need.
The while loop
The condition is checked before each pass. If it's false at the very start, the body never runs.
class Main {
public static void main(String[] args) {
int countdown = 5;
while (countdown > 0) {
System.out.println(countdown + "...");
countdown--;
}
System.out.println("Liftoff!");
}
}5...
4...
3...
2...
1...
Liftoff!
Something inside the loop must eventually make the condition false — here countdown--. Otherwise you have an infinite loop and the program never ends.
A loop with an unknown number of steps
How many years until savings double at 7% interest? We can't easily know in advance, so while is a natural fit:
class Main {
public static void main(String[] args) {
double balance = 1000;
int years = 0;
while (balance < 2000) {
balance = balance * 1.07;
years++;
}
System.out.printf("Doubled after %d years: %.2f%n", years, balance);
}
}Doubled after 11 years: 2104.85
Another classic: summing the digits of a number by repeatedly taking the last digit:
class Main {
public static void main(String[] args) {
int n = 90417;
int sum = 0;
while (n > 0) {
sum += n % 10; // last digit
n /= 10; // remove last digit
}
System.out.println("Digit sum: " + sum);
}
}Digit sum: 21
The do/while loop
A do...while loop checks its condition after the body, so the body always runs at least once. Note the semicolon after the condition.
class Main {
public static void main(String[] args) {
int attempts = 10;
do {
System.out.println("Attempt " + attempts);
attempts++;
} while (attempts < 3);
System.out.println("Final value: " + attempts);
}
}Attempt 10
Final value: 11
The condition attempts < 3 was false from the start, yet the body ran once. A typical use is a menu or input prompt that must be shown before you can check the user's answer.
while |
do...while |
|
|---|---|---|
| Condition checked | before each pass | after each pass |
| Minimum runs | 0 | 1 |
| Syntax ends with | } |
} while (cond); |
Avoiding infinite loops
int i = 0;
while (i < 5) {
System.out.println(i);
// forgot i++ -> prints 0 forever
}Check three things for every loop: the variable is initialised, the condition tests it, and the body changes it. Sometimes while (true) is written on purpose, together with a break that leaves the loop — see the Break/Continue chapter.
Test yourself
How many times does the body run? int i = 10; while (i < 10) { i++; }
- 0
- 1
- 10
- Forever
What is guaranteed about a do...while loop?
- It never runs
- Its body runs at least once
- It runs exactly once
- It can't use break
What is printed? int x = 1; while (x < 20) { x *= 3; } System.out.println(x);
- 9
- 18
- 27
- 20