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
- The program enters the for loop. The first part, the initialization (int i = 1), is executed once.
- 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.
- The code inside the loop body is executed. The string "Iteration: " is created and will be added to the string pool.
- The value of i (1) is concatenated with the string, and the result is printed to the console.
- After the loop body, the update statement (i++) is executed. The value of i is incremented to 2.
- The condition (i <= 5) is checked again. Since 2 is less than or equal to 5, the condition is true.
- The loop body executes again, printing the current value of i.
- The update statement (i++) executes, incrementing i to 3.
- The condition (3 <= 5) is true. The loop continues.
- The loop body prints "Iteration: 3".
- i is incremented to 4.
- The condition (4 <= 5) is true.
- The loop body prints "Iteration: 4".
- i is incremented to 5.
- The condition (5 <= 5) is true.
- The loop body prints "Iteration: 5".
- i is incremented to 6.
- The condition (i <= 5) is checked. Since 6 is not less than or equal to 5, the condition is false. The loop terminates.
- Execution continues to the next statement after the loop. The variable i is now out of scope and removed from the stack.
- The final message is printed to the console.