Java For Loop

The for loop in Java is used to execute a block of code a specific number of times. It's typically used when the number of iterations is known before entering the loop.

Key Topics

1. Syntax

for (initialization; condition; update) {
    // Code to be executed
}

2. Example

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Count: " + i);
        }
    }
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

3. Enhanced For Loop

The enhanced for loop (also known as the for-each loop) is used to iterate over arrays and collections.

for (type variableName : arrayName) {
    // Code to be executed
}

Key Takeaways

  • The for loop is ideal when the number of iterations is known.
  • Initialization, condition, and update statements control the loop execution.
  • The enhanced for loop simplifies iteration over arrays and collections.