DEV Community

Sudhakar V
Sudhakar V

Posted on

For Loop In java

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
}
Enter fullscreen mode Exit fullscreen mode

🔍 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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🔎 Output:

i = 1
i = 2
i = 3
i = 4
i = 5
Enter fullscreen mode Exit fullscreen mode

🔁 Reverse Loop Example:

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

Output:

5
4
3
2
1
Enter fullscreen mode Exit fullscreen mode

💥 Infinite Loop (Be careful!)

for (;;) {
    System.out.println("This runs forever!");
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

🆚 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! ⭐📐

Top comments (0)