Core Java Fundamentals ยท Loops

For Loop

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

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.