Let’s go deep into the for loop in Java — one of the most common and powerful looping structures.


🔁 What is a for Loop?

A for loop allows you to execute a block of code a known number of times. It's perfect when you know in advance how many times you want to run the loop.


🧠 Syntax:

for (initialization; condition; update) {
    // Code to execute in each loop iteration
}

🔍 Parts of a for Loop:

Part Description
Initialization Runs once at the start. Sets up the loop counter.
Condition Checked before each iteration. Loop runs as long as it's true.
Update Runs after each iteration. Usually used to increment/decrement counter.

✅ Basic Example:

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

🔎 Output:

i = 1
i = 2
i = 3
i = 4
i = 5

🔁 Reverse Loop Example:

for (int i = 5; i >= 1; i--) {
    System.out.println(i);
}

Output:

5
4
3
2
1

💥 Infinite Loop (Be careful!)

for (;;) {
    System.out.println("This runs forever!");
}

If you leave all 3 parts empty, it becomes an infinite loop. Use with caution!


🔍 Nested for Loops:

Used for patterns or matrices:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println("i=" + i + ", j=" + j);
    }
}

🆚 Compared with while and do-while:

Feature for loop while loop do-while loop
Condition check Before each iteration Before each iteration After each iteration
Usage When count is known When count is unknown Must run at least once

🎯 Common Use Cases:

  • Iterating through arrays
  • Printing patterns
  • Counting logic
  • Repeated tasks with a known range

💬 Want a pattern example using for loop? Like pyramid, star, or number triangle? Just say the word! ⭐📐