For Loop

Learn how to execute a block of code a specific number of times using the for loop.

Java · beginner · 15 min · 20 steps · free

What you'll learn

ForLoopDemo.java

public class ForLoopDemo {
    public static void main(String[] args) {
        // This for loop will print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration: " + i);
        }
        
        System.out.println("Loop finished.");
    }
}

Step by step

  1. The program enters the for loop. The first part, the initialization (int i = 1), is executed once.
  2. Next, the condition (i <= 5) is checked. Since 1 is less than or equal to 5, the condition is true, and we enter the loop body.
  3. The code inside the loop body is executed. The string "Iteration: " is created and will be added to the string pool.
  4. The value of i (1) is concatenated with the string, and the result is printed to the console.
  5. After the loop body, the update statement (i++) is executed. The value of i is incremented to 2.
  6. The condition (i <= 5) is checked again. Since 2 is less than or equal to 5, the condition is true.
  7. The loop body executes again, printing the current value of i.
  8. The update statement (i++) executes, incrementing i to 3.
  9. The condition (3 <= 5) is true. The loop continues.
  10. The loop body prints "Iteration: 3".
  11. i is incremented to 4.
  12. The condition (4 <= 5) is true.
  13. The loop body prints "Iteration: 4".
  14. i is incremented to 5.
  15. The condition (5 <= 5) is true.
  16. The loop body prints "Iteration: 5".
  17. i is incremented to 6.
  18. The condition (i <= 5) is checked. Since 6 is not less than or equal to 5, the condition is false. The loop terminates.
  19. Execution continues to the next statement after the loop. The variable i is now out of scope and removed from the stack.
  20. The final message is printed to the console.

Common mistakes

Best practices

Key takeaways

Check yourself

How many times does int i = 1 run in this loop?

Answer: Once. The initialization runs once, before the first condition check.

With i <= 5, what is i when the loop stops?

Answer: 6. The loop stops when the condition first fails, which happens when i becomes 6.

What happens if <= is changed to <?

Answer: It prints 1 to 4. With i < 5, the loop stops as soon as i reaches 5, so 5 is never printed.

·

More in Loops