By WebNest Studio Engineering Team
Java - Core Tutorial
Java For Loop
The for loop is Java's standard construct for repeating a block of code a known or countable number of times. It packages initialization, a continuation condition, and an update step into one compact header, which keeps loop-control logic in a single, easy-to-scan place instead of scattered across the loop body.
Because all three parts of the header are visible together, the for loop communicates intent clearly: a reader immediately sees where the counter starts, when the loop stops, and how the counter changes on every pass, without having to hunt through the loop body for that information.
Why it matters
The for loop is the standard way to repeat work a known number of times, and its three parts run in an order that is easy to get slightly wrong. Off-by-one errors — looping once too many or once too few — are among the most common bugs in any language, and they come from misreading exactly when the condition is checked and when the update happens.
Anatomy of the for Loop
The header has the form for (initialization; condition; update). Initialization runs once before the loop starts, typically declaring a counter variable. The condition is checked before every iteration, including the first — if it is false immediately, the loop body never runs at all. The update expression runs after each iteration completes, before the condition is checked again.
Watch: How the Java For Loop Works
A quick video on the order a for loop runs its initialization, condition, body and update.
How the for Loop Runs, Step by Step
The three header parts are written together but are not executed together. For for (int i = 1; i <= 3; i++) { body }, Java runs them in this exact order:
- 1. Initialization —
int i = 1runs exactly once, before anything else. - 2. Condition —
i <= 3is checked. If it is false, the loop ends immediately and the body is skipped. - 3. Body — the statements inside the braces run once.
- 4. Update —
i++runs after the body, not before it. - 5. Repeat from step 2 — the condition is checked again with the new value, and steps 2 to 4 repeat until the condition becomes false.
Tracing an Iteration Table
The easiest way to predict what a loop does is to trace it in a small table: one row per condition check, recording the counter's value, whether the condition is true, and what the body does. For for (int i = 1; i <= 3; i++) the condition is checked four times (i = 1, 2, 3 and finally 4) but the body runs only three times, because the fourth check is the one that fails and ends the loop. The condition is always checked one more time than the body runs, and that single extra check is where most off-by-one bugs come from.
Nested for Loops
A for loop can contain another for loop. The inner loop runs through all of its iterations for every single iteration of the outer loop, so an outer loop of 3 and an inner loop of 4 execute the inner body 3 × 4 = 12 times. Nested loops are the standard tool for rows-and-columns work: grids, 2D arrays, multiplication tables, and printed patterns. Give each loop its own counter name (commonly i for rows and j for columns), and remember that a plain break only exits the innermost loop it sits in.
Multiple Expressions and Infinite Loops
Java allows comma-separated multiple initializations and multiple update expressions in a single for header, which is useful for loops that track two related counters moving in opposite directions. Any of the three header parts can also be omitted; omitting all three, as in for (;;), produces an intentional infinite loop that must be stopped from inside the body, usually with a break statement or a return.
Scope of the Loop Variable
A variable declared in the initialization section (e.g. int i) is scoped only to the for loop itself — it does not exist before the loop and cannot be referenced after it ends. This prevents loop counters from accidentally leaking into and cluttering the surrounding method's namespace.
Examples
A simple counting loop and a loop with two update expressions moving toward each other
public class ForLoopDemo {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
for (int i = 1, j = 5; i <= j; i++, j--) {
System.out.println(i + " " + j);
}
}
}
Sum: 15
1 5
2 4
3 3
Printing every step to see the real execution order of init, condition, body, and update
public class ForLoopTrace {
static boolean check(int i) {
boolean result = i <= 3;
System.out.println("check i=" + i + " -> " + result);
return result;
}
public static void main(String[] args) {
for (int i = init(); check(i); i = update(i)) {
System.out.println(" body i=" + i);
}
System.out.println("loop finished");
}
static int init() {
System.out.println("init i=1");
return 1;
}
static int update(int i) {
System.out.println(" update i=" + i + " -> " + (i + 1));
return i + 1;
}
}
init i=1
check i=1 -> true
body i=1
update i=1 -> 2
check i=2 -> true
body i=2
update i=2 -> 3
check i=3 -> true
body i=3
update i=3 -> 4
check i=4 -> false
loop finished
Nested for loops: the inner loop completes fully for each outer iteration
public class NestedForDemo {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}
*
* *
* * *
1 2 3
2 4 6
3 6 9
Common Mistakes
- Off-by-one errors from using "<=" versus "<" incorrectly, causing the loop to run one time too many or too few.
- Putting a semicolon right after the header — "for (int i = 0; i < 5; i++);" — which makes the loop body an empty statement, so the block below it runs only once after the loop finishes.
- Assuming the update (i++) runs before the body on each pass; it always runs after the body, just before the next condition check.
- Reusing the same counter name (i) for an inner nested loop, which does not compile when the outer i is still in scope.
- Modifying the loop counter inside the body in addition to the header's update expression, causing confusing, hard-to-predict iteration counts.
- Trying to use the loop variable after the loop ends, not realizing it goes out of scope once the for block closes.
- Writing "for (;;)" without an internal break condition, creating an unintended infinite loop that hangs the program.
Exercise
Use a for loop to add up all the even numbers from 2 to 100 inclusive and print the total.
Expected output: 2550
public class SumOfEvens {
public static void main(String[] args) {
int sum = 0;
// TODO: loop over the even numbers from 2 to 100 and add each to sum
System.out.println(sum);
}
}
Show hints
- The update expression does not have to be
i++;i += 2steps through even numbers directly. - Use
<=so that 100 itself is included.
Show solution
public class SumOfEvens {
public static void main(String[] args) {
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
System.out.println(sum); // 2550
}
}
Quick quiz
1. How many times does the body of for (int i = 0; i < 5; i++)</code> run?
A. 5B. 4C. 6D. It never stops
Show answer
A. i takes the values 0, 1, 2, 3 and 4. When i becomes 5 the condition is false and the loop ends.
2. What happens with for (int i = 0; i < 3; i++) { } System.out.println(i);</code>?
A. It prints 3B. It does not compileC. It prints 2D. It prints 0
Show answer
Show answerB. A variable declared in the for header exists only inside the loop. Using i after the loop is a compile error.
3. What does for (;;) { } do?
A. It does not compileB. It runs onceC. It runs foreverD. It never runs
Show answer
Show answerC. All three parts are optional. A missing condition is treated as true, so this is an infinite loop.
Interview questions
Interview questionsIn what order do the parts of a for loop execute?
Show answer
Show answerThe initialisation runs once. Then the condition is checked; if it is true the body runs, then the update expression runs, and the condition is checked again. As soon as the condition is false the loop ends.
Two consequences: the body may run zero times, and the update runs after the body, not before it.
Is there any difference between i++ and ++i in the update part of a for loop?
Show answer
Show answerNot in the result. The update expression's value is discarded, so both simply add one to i. The difference between prefix and postfix only matters when the value of the expression is used, as in int x = i++;.
Key Points to Remember
- The header runs initialization once, checks the condition before every iteration, and runs the update after every iteration.
- Execution order is: init → condition → body → update → condition → body → update … until the condition is false.
- The condition is always checked one more time than the body runs — the final, failing check is what ends the loop.
- In nested loops the inner loop runs to completion for every outer iteration, so the total inner-body count is outer × inner.
- If the condition is false on the very first check, the loop body never executes.
- A for loop's counter variable is scoped to the loop and does not exist outside it.
- for (;;) with all header parts omitted creates an infinite loop that needs an internal break or return.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering