Course contentsShow
← Java
Lesson 166 of 2,8704. Control Flow StructuresFree lesson

Executing for Loops: Step-by-Step Evaluation Order

Understand how the JVM evaluates initialization once, then alternates between condition check and loop body execution.

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:

  1. Initialization – Executes exactly once, before anything else
  2. Condition check – Tests whether to enter/continue the loop
  3. Loop body – Runs if the condition was true
  4. Update – Executes after the body completes
  5. 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:

  1. int i = 0 – Initialize i (happens once only)
  2. i < 3? → true (0 < 3)
  3. Print 0
  4. i++ → i becomes 1
  5. i < 3? → true (1 < 3)
  6. Print 1
  7. i++ → i becomes 2
  8. i < 3? → true (2 < 3)
  9. Print 2
  10. i++ → i becomes 3
  11. i < 3? → false (3 is not < 3)
  12. 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.