Executing for Loops: Step-by-Step Evaluation Order
You'll learn exactly how Java processes each part of a for loop, in what order, every time the loop runs.
The Four-Part Dance
When you write a for loop, it has up to four distinct parts:
for (initialization; condition; update) {
// loop body
}
Here's the precise order the JVM follows:
- Initialization – Executes exactly once, before anything else
- Condition check – Tests whether to enter/continue the loop
- Loop body – Runs if the condition was
true - Update – Executes after the body completes
- Back to step 2 – Repeats condition → body → update until condition becomes
false
Step-by-Step Example
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
Execution trace:
int i = 0– Initializei(happens once only)i < 3? →true(0 < 3)- Print
0 i++→ibecomes 1i < 3? →true(1 < 3)- Print
1 i++→ibecomes 2i < 3? →true(2 < 3)- Print
2 i++→ibecomes 3i < 3? →false(3 is not < 3)- Loop exits
Think of It Like a Recipe
The initialization is gathering your ingredients (once). Then you taste-test (condition), cook (body), stir (update), and repeat the taste-test-cook-stir cycle until done.
Key Takeaway: The for loop initializes once, then alternates between checking the condition and executing the body + update until the condition becomes false.