← Back to Chapters

Java for Loop

? Java for Loop

? Quick Overview

The for loop in Java is used to execute a block of code a fixed number of times. It is commonly used when the number of iterations is known in advance.

? Key Concepts

  • Best suited for known iteration counts
  • Combines initialization, condition, and increment
  • Makes code concise and readable

? Syntax / Theory

The Java for loop consists of three parts:

  • Initialization – runs once at the start
  • Condition – checked before each iteration
  • Update – runs after each loop iteration
? View Code Example
// Basic syntax of a for loop
for(initialization; condition; update){
    // code to be executed repeatedly
}

? Code Example

? View Code Example
// Print numbers from 1 to 5 using for loop
class ForLoopDemo {
    public static void main(String[] args) {
        for(int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

? Live Output / Explanation

Output:

1
2
3
4
5

The loop starts with i = 1, runs while i <= 5, and increments i after each iteration.

? Interactive Simulator

Modify the values below and run the code to see how the Java loop behaves logically:

for (int i = ; i <= ; i = i + ) { }
Output will appear here...

✅ Tips & Best Practices

  • Use meaningful loop variable names when possible
  • Avoid infinite loops by ensuring condition becomes false
  • Prefer for loop when iteration count is fixed

? Try It Yourself

  • Print even numbers from 1 to 20
  • Display the multiplication table of a number
  • Calculate the sum of first 10 natural numbers