Java For Loop (With Easy Explanation + Real Examples)

βœ… What is a For Loop?

In Java, the for loop is a control structure used to repeat a block of code a certain number of times. It is best used when the number of iterations is known beforehand. It combines initialization, condition-checking, and increment/decrement in one line, making the loop concise and powerful.


🧠 Syntax of the For Loop

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

Explanation:

  • Initialization: Runs once at the beginning. Usually used to declare and initialize a loop control variable.

  • Condition: Checked before each iteration. If true, the loop continues.

  • Update: Executed after every iteration. Usually used to update the loop control variable.


🎯 Example 1: Print Numbers from 1 to 5

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

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

🎯 Example 2: Print Even Numbers from 2 to 10

public class EvenNumbers {
public static void main(String[] args) {
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
}
}

Output:

2
4
6
8
10

πŸŒ€ Infinite Loop Using For

You can also create an infinite loop by omitting all three parts:

for (;;) {
System.out.println("This is an infinite loop!");
}

⚠️ This will run forever unless you use a break statement or stop the program manually.


πŸ’‘ Using Multiple Variables in a For Loop

You can declare and update multiple variables in a for loop:

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

Output:

i = 1, j = 5
i = 2, j = 4
i = 3, j = 3
i = 4, j = 2
i = 5, j = 1

βœ… When to Use a For Loop

  • You know how many times the loop should run.

  • You want compact loop control with initialization, condition, and update in one place.

  • You’re iterating over arrays or performing counters.

Related Posts