Java Loops: while, do-while and for
Repeat work in Java with while, do-while and for loops: how each one tests its condition, a savings-target calculator, counting team combinations, counting down, the scope of loop variables, floating-point loop traps, infinite loops, and how to choose the right loop.
kvi5hnuCode Sprout team member9 min readOn this page
A loop repeats a statement (usually a block) while some condition holds. Java has three classic loops, all inherited from C:
| Loop | Tests the condition | Body runs |
|---|---|---|
while (cond) body | before each pass | 0 or more times |
do body while (cond); | after each pass | at least once |
for (init; cond; update) body | before each pass | 0 or more times; built-in counter |
There's also the enhanced for loop (for (var x : collection)), which visits each element of an array or collection. It's covered with arrays later in this part.

The while Loop
while (condition) statement
The condition is tested first. If it's true, the body runs and the condition is tested again, and so on. As soon as it's false, execution continues after the loop. If the condition is false from the start, the body never runs.
Example: how long until you hit a savings target?
Say you put the same amount aside each month, the pot earns a little interest, and you want to know how many months it takes to reach a target:
public class Solution {
public static void main(String[] args) {
double target = 1200;
double deposit = 100;
double ratePercent = 0.5; // per month
double saved = 0;
int months = 0;
while (saved < target) {
saved += deposit;
double interest = saved * ratePercent / 100;
saved += interest;
months++;
}
System.out.printf("Target reached after %d months (saved %.2f)%n", months, saved);
}
}
Target reached after 12 months (saved 1239.72)
One trip through the body stands for one month. The loop repeats while the pot is still short of the target, and months counts the trips. (Real savings plans also have to deal with fees, taxes and changing rates.)
To ask the user for the numbers instead, read target, deposit and ratePercent with a Scanner:
Scanner in = new Scanner(System.in);
System.out.print("Savings target: ");
double target = in.nextDouble();
System.out.print("Monthly deposit: ");
double deposit = in.nextDouble();
System.out.print("Monthly interest rate in %: ");
double ratePercent = in.nextDouble();
The do/while Loop
Sometimes the body must run at least once before the condition makes sense. For example, a program must show the current total before it can ask whether that's enough. The do/while loop tests at the bottom:
do statement while (condition);
Note the semicolon after the condition.
public class Solution {
public static void main(String[] args) {
double deposit = 100;
double ratePercent = 0.5;
double saved = 0;
int month = 0;
String[] answers = {"N", "N", "Y"}; // simulated user input
int next = 0;
String input;
do {
saved += deposit;
saved += saved * ratePercent / 100;
month++;
System.out.printf("After month %d you have %,.2f%n", month, saved);
input = answers[next++];
System.out.println("Buy the bike now? (Y/N) " + input);
} while (input.equals("N"));
}
}
After month 1 you have 100.50
Buy the bike now? (Y/N) N
After month 2 you have 201.50
Buy the bike now? (Y/N) N
After month 3 you have 303.01
Buy the bike now? (Y/N) Y
In a real program, the answer comes from input = in.next();. The canned answers here let the example run without a keyboard.
Notice that input is declared before the loop. A variable declared inside the do block goes out of scope at the closing brace, so the while (…) condition couldn't see it.
The for Loop
The for loop is designed for iterations controlled by a counter (or similar variable) that is updated on every pass:
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
The header has three slots, separated by semicolons:
- Initialization,
int i = 1: runs once, before anything else. - Condition,
i <= 10: tested before every pass; the loop ends when it's false. - Update,
i++: runs after every pass, before the condition is tested again.
This prints 1 to 10. Counting down works the same way:
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
}
System.out.println("Go!");
A for loop is a compact while loop
These two are equivalent:
for (int i = 5; i > 0; i--) {
System.out.println("Starting in " + i);
}
int i = 5;
while (i > 0) {
System.out.println("Starting in " + i);
i--;
}
The for form keeps everything about the counter (start, end, step) in one line, which makes the loop easier to understand at a glance. (There's one small difference: continue in a for loop still runs the update, as the next-but-one article explains.)
Scope of the loop variable
A variable declared in the initialization slot is in scope only in the loop (header and body):
for (int i = 1; i <= 10; i++) {
...
}
// i is no longer defined here
To use the final value after the loop, declare the variable before it:
int i;
for (i = 1; i * i <= 50; i++) { }
System.out.println(i); // 8: the first i whose square exceeds 50
Because the scope ends with the loop, separate for loops can each declare their own i:
for (int i = 1; i <= 10; i++) { ... }
for (int i = 11; i <= 20; i++) { ... } // OK: a new variable
Several variables
The first slot can declare several variables of the same type, and the third slot can contain several comma-separated expressions:
for (int i = 1, j = 10; i < j; i++, j--) {
System.out.print(i + ":" + j + " "); // 1:10 2:9 3:8 4:7 5:6
}
It's legal but stretches the idea of a counter loop. Use it sparingly, for example for two indexes moving toward each other.
Example: how many different teams?
If a coach picks k players from a squad of n, ignoring order, the number of different teams is:
n × (n − 1) × (n − 2) × … × (n − k + 1) / (1 × 2 × 3 × … × k)
That's the binomial coefficient "n choose k". A for loop computes it step by step:
public class Solution {
public static void main(String[] args) {
int n = 40;
int k = 5;
long teams = 1;
for (int i = 1; i <= k; i++) {
teams = teams * (n - i + 1) / i;
}
System.out.println("Possible teams: " + teams);
}
}
Possible teams: 658008
Why is the division always exact? After step i, teams equals "n choose i", which is always a whole number. Multiplying before dividing keeps it exact, and that's why the expression isn't written as teams * ((n - i + 1) / i), where integer division would truncate. For large n and k, even long overflows; the big numbers article redoes this with BigInteger.
Floating-Point Loop Counters: A Trap
Never control a loop by testing a floating-point counter for exact equality:
for (double x = 0; x != 10; x += 0.1) { ... } // may never end!
0.1 has no exact binary representation, so the rounding errors accumulate. After 100 additions, x is 9.99999999999998, not 10, and the next value is about 10.09999999999998. The condition x != 10 stays true forever.
Safer alternatives:
- Use
<instead of!=:for (double x = 0; x < 10; x += 0.1). It always terminates (though the number of passes may still be off by one). - Better: count with an integer and compute the floating-point value:
for (int i = 0; i <= 100; i++) {
double x = i * 0.1; // 0.0, 0.1, ..., 10.0, exactly 101 values
...
}
Infinite Loops
A loop whose condition never becomes false runs forever. Accidental infinite loops usually come from forgetting to update the variable in the condition:
int i = 0;
while (i < 10) {
System.out.println(i); // forgot i++: prints 0 forever
}
Stop a runaway program with Ctrl+C in a terminal, or the red stop button in your IDE.
Sometimes an infinite loop is intended: servers that process requests until shut down, game loops, or loops exited from the middle with break (next-but-one article). The idioms are while (true) { … } and for (;;) { … }.
Choosing a Loop
| Situation | Loop |
|---|---|
| Known number of passes, or stepping a counter through a range | for |
| Visiting every element of an array or collection | enhanced for (for (var x : items)) |
| Repeat while a condition holds, possibly zero times (reading input, searching, simulations) | while |
| The body must run once before the condition can be tested | do/while |
Beyond these, modern Java often replaces explicit loops over data with streams (list.stream().filter(...).map(...)), a declarative style covered later in the course.
Common questions
Which loop is fastest?
For the same work they compile to nearly identical bytecode, and the JIT optimises them equally. Choose the loop that expresses your intent: for for counting, the enhanced for for visiting elements, while for "until something happens", and do/while for "at least once".
Can I change the loop variable inside a for body?
The compiler allows it, but it makes the loop hard to follow, because readers expect the header to describe the whole iteration. If you need to skip ahead or change the step, rewrite it as a while loop with explicit updates.
How do I loop a fixed number of times when I don't need the counter?
Write for (int i = 0; i < n; i++). A lone _ can't be used as the counter of a classic for loop, because the counter is used in the condition and update. With streams, IntStream.range(0, n).forEach(_ -> work()) uses _ for the unused lambda parameter (Java 22).
What does for (;;) mean?
All three slots are empty, and an empty condition counts as true, so it is an infinite loop, the same as while (true). It must be left with break, return or an exception. Both forms are idiomatic.
Why should I count with integers instead of double?
Every += 0.1 adds a tiny rounding error, so the counter drifts and may skip or overshoot the end value. Counting with an int and computing x = start + i * step keeps each value as accurate as possible and makes the number of passes exact.
Summary
while (cond) bodytests first: zero or more passes.do body while (cond);tests last: at least one pass. Declare variables used in the condition before the loop, and don't forget the semicolon.for (init; cond; update) bodykeeps counter logic in one header. It's equivalent to awhileloop with the init before it and the update at the end of the body.- A variable declared in a
forheader is scoped to the loop; declare it outside if you need it afterwards. - Never test floating-point loop counters with
==/!=; loop over integers and compute the fractional value. - Make sure something in the body moves the loop toward its end. Ctrl+C stops a runaway program.
Practice Questions
How many times does the body of while (n > 0) { n -= 3; } run if n starts at 10? And if n starts at 0?
Starting at 10: n takes the values 10 → 7 → 4 → 1 → −2, so the body runs 4 times. Starting at 0, the condition is false immediately: 0 times.
Rewrite for (int i = 0; i < 5; i++) System.out.println(i * i); as a while loop.
int i = 0;
while (i < 5) {
System.out.println(i * i);
i++;
}
Why does this not compile? do { String answer = in.next(); } while (answer.equals("again"));
answer is declared inside the do block, so its scope ends at the closing brace, and the while condition can't see it. Declare String answer; before the loop and assign it inside.
Write a for loop that prints the even numbers from 20 down to 2.
for (int i = 20; i >= 2; i -= 2) {
System.out.println(i);
}
Why is teams = teams * (n - i + 1) / i; correct, while teams = teams * ((n - i + 1) / i); gives wrong results?
In the second version, (n - i + 1) / i is integer division and is truncated before multiplying, losing information. In the first, * and / are evaluated left to right; the product is divisible by i because it equals i × "n choose i", so the division is exact.
Will for (float f = 0f; f != 1f; f += 0.1f) terminate?
Not reliably. 0.1f isn't exactly representable, so after ten additions f isn't exactly 1f (it's about 1.0000001), and the loop continues forever. Loop over an integer counter instead and compute f = i * 0.1f, or use <.
Previous: Java Block Scope and if/else Statements
Next: The Java switch Statement: Four Forms of switch and Fall-Through
Related reading
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java Streams Explained: From Loops to Stream Pipelines
- Your First Java Program Explained: Classes, main, Statements and Comments
- Java Block Scope and if/else Statements

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.