Java loops repeat instructions while a rule permits another iteration. A for loop groups initialization, condition and update in one header. A while loop checks its condition before each iteration. A do-while loop runs its body before checking, so it executes at least once.
Choose a form that makes the stopping rule visible. Repeating a known number of times often fits for, waiting for a changing condition fits while, and performing an action before deciding whether to repeat can fit do-while. The language permits overlap, but readability improves when the form matches the task.
Trace the order of a for loop
A basic for header has three parts separated by semicolons: initialization, condition and update. Initialization happens once. Before every iteration, Java evaluates the condition. If it is true, the body runs; the update then runs before the next condition check. If the condition is false, the loop ends without running its body again.
In for (int i = 0; i < 3; i++), the body sees zero, one and two. It never sees three because the condition rejects that value. A counter declared in the header is scoped to the loop. Use i for a short local index if its role is obvious; use a descriptive name such as attempt when it represents a meaningful count.
A while loop checks before acting
A while loop repeatedly checks a boolean condition before executing its body. If the initial condition is false, the body runs zero times. Any state required to make the condition eventually false must change somewhere during execution. That change may come from the body, input or another explicitly managed mechanism.
For a countdown, initialize the remaining count, print it while it is positive and decrease it inside the body. Forgetting the decrease leaves the condition permanently true. Not every loop uses a numeric counter: reading lines until the reader reaches the end is also a while pattern. Make the source of progress visible so a reader can explain why the loop terminates.
A do-while loop acts before checking
The do-while form begins with do and a body, followed by while (condition);. The semicolon after that condition is part of this statement’s syntax. Because the body comes first, it executes once even when the condition would initially be false.
This can suit a menu that must be displayed before the program decides whether to show it again. It is less suitable when an empty or invalid input should cause no action at all. Do not choose do-while merely to reduce a line of code; choose it when one mandatory first attempt belongs to the behavior. The later condition checks use the state after that attempt, including any changes made inside the body.
Counters and boundary choices
For indexes into an array of length n, the conventional valid range is zero through n - 1. The condition index < n includes exactly those indexes. Using index <= n permits the invalid index n. For human-facing counts from one through n, a different condition may be correct: counter <= n can include the final item.
Decide what the variable represents before choosing its initial value and comparison. A count, an index and a remaining quantity have different natural boundaries. Test zero iterations, one iteration and several iterations. If an update skips values by two, also test whether the stopping rule behaves correctly when the endpoint is odd. A loop can compile and still execute one too many or one too few times.
Keep the loop body purposeful
A loop body should describe one repeated unit of work. If it grows long, move a coherent operation into a helper method, but keep the progression and stopping rule easy to locate. An accumulator such as total should usually be initialized before the loop, then updated inside it. Initializing it inside resets it on every iteration.
An intentional infinite loop uses a visibly deliberate condition, often while (true), with an explicit exit elsewhere. Such a design needs a clear reason and a reliable stopping path. For beginner counting tasks, a finite condition is easier to inspect. Remember that print output alone does not prove progress: a loop can print the same message forever while never changing the state controlling its condition.
Practice with explained solutions
Task 1. Sum integers from one through four using an accumulator declared before a for loop.
Solution. Initialize total to zero and add each counter value. The result is ten; the counter should visit 1, 2, 3 and 4.
Task 2. Choose between while and do-while when an empty collection must result in no processing.
Solution. Use a prechecked form such as while or a suitable for loop. do-while would force one body execution even when no item exists.
Java Summary
- for and while check before executing; do-while guarantees one initial execution.
- Choose boundaries that match an index, count or remaining quantity.
- Keep accumulators outside the loop and make progress toward termination visible.
- Continue with nested and enhanced loops.
Java Examples
Each example shows the code, the output it produces and what each part does.
Repeat a known number of times
Save this complete program as NumberedSteps.java. Compile with javac --release 17 NumberedSteps.java and run with java NumberedSteps.
public class NumberedSteps {
public static void main(String[] args) {
for (int step = 1; step <= 3; step++) {
System.out.println("Step " + step);
}
}
}Step 1
Step 2
Step 3Line-by-line explanation
- Lines 1 to 7Initialization starts step at one. Each condition permits the current value through three, and each update adds one. After printing Step 3, the update makes step four and the condition fails. The counter is a human-facing step number rather than an array index, so an inclusive endpoint is intentional here.
Accumulate during a countdown
Save this complete program as CountdownTotal.java. Compile with javac --release 17 CountdownTotal.java and run with java CountdownTotal.
public class CountdownTotal {
public static void main(String[] args) {
int remaining = 3;
int total = 0;
while (remaining > 0) {
total += remaining;
remaining--;
}
System.out.println(total);
System.out.println(remaining);
}
}6
0Line-by-line explanation
- Lines 1 to 8The accumulator receives three, then two, then one, producing six. Decreasing remaining inside the loop makes the condition eventually false.
- Lines 9 to 12The final value zero explains termination. If total were declared and initialized inside the body, earlier additions would not survive into later iterations, defeating the intended accumulation.
Observe the mandatory first iteration
Save this complete program as FirstAttempt.java. Compile with javac --release 17 FirstAttempt.java and run with java FirstAttempt.
public class FirstAttempt {
public static void main(String[] args) {
int attempts = 0;
do {
attempts++;
System.out.println("Attempt " + attempts);
} while (attempts < 0);
}
}Attempt 1Line-by-line explanation
- Lines 1 to 9The body executes before Java asks whether attempts is less than zero. Incrementing creates the first attempt, then the condition is false and the loop stops. A while loop with the same initially false condition would execute nothing. This deliberately small comparison isolates the timing difference; a real retry loop would use a meaningful allowed-attempts rule.
Common Java Mistakes
Updating a counter in the wrong direction
An update in the wrong direction can make a loop infinite. If remaining must reach zero from a positive start, increasing it cannot satisfy that intention. Likewise, changing a for counter again inside the body can skip expected iterations. Trace the exact counter value before the condition, inside the body and after the update rather than assuming the header tells the whole story.
Java FAQ
Can every for loop be rewritten as while?
Many basic loops can, provided you preserve initialization, condition and update order. continue behavior can complicate a careless translation because a for update still occurs after a continued iteration.
Which loop is fastest?
Choose the clearest correct form first. For ordinary beginner tasks, algorithm and work inside the body matter far more than stylistic loop selection.
When should I use do-while instead of while?
Use do-while when the body must run at least once before the condition can be checked, such as showing a menu and then asking whether to repeat, or reading input and then validating it. If the body may need to run zero times, use while.
Can a for loop use two counters?
Yes. Declare and update several variables with commas: for (int i = 0, j = n - 1; i < j; i++, j--) moves one index forwards and another backwards, which is the usual way to reverse an array or check a palindrome. Both variables must have the same type.
Can I use the loop counter after a for loop ends?
Not if it was declared in the loop header: its scope ends with the loop. If you need the final value, for example the position where a search stopped, declare the variable before the loop and only update it in the header.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
How many iterations occur for i = 0; i < 1; i++?
Where should a running total be initialized?
Java Quiz
2 questions to check what you learned.
Which loop checks its condition after the first body execution?
- do-while
- while
- Basic for
What values does i take inside for (int i = 0; i < 3; i++)?
- 0, 1, 2
- 1, 2, 3
- 0, 1, 2, 3