0
Explore
0

for Loop in Java – Mastering Iteration Step-by-Step

Updated on July 27, 2025

When learning Java programming, loops are one of the most important concepts to understand because they allow us to repeat tasks efficiently. In Java, the for loop is one of the most commonly used loop structures.

This tutorial will walk you through everything about for loops in Java.

What is a for loop?

A for loop is a control flow statement used to repeat a block of code a certain number of times. It is best used when you know in advance how many times you want to execute a statement or block of statements.

Syntax of the for Loop

for (initialization; condition; update) {
    // body of the loop
}

Let’s break it down:

PartDescription
initializationThis is where you declare and initialize the loop control variable (like int i = 0). It runs only once at the beginning.
conditionThis is the condition that gets evaluated before each iteration. If it returns true, the loop continues. If it returns false, the loop stops.
updateThis is executed after every iteration. It usually increases or decreases the loop variable.
{ body }This contains the code that runs on every iteration.

Example of For Loop (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(i);
        }
    }
}

Output:

1
2
3
4
5

Step-by-Step Explanation:

1. Class and main method

public class ForLoopExample {
    public static void main(String[] args) {
  • This is the starting point of the program.
  • The main method is where the program execution begins.

2. For loop

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

The for loop is used to repeat a task, in this case, printing numbers from 1 to 5.

Let’s break the loop into parts:

  • Initialization:
    int i = 1;
    → A variable i is created and set to 1. This is the starting point of the loop.
  • Condition:
    i <= 5;
    → Before each loop run, Java checks this condition.
    If it’s true, the loop runs. If false, it stops.
  • Update:
    i++
    → After every loop execution, i increases by 1.

3. Inside the loop

System.out.println(i);
  • This line prints the current value of i to the screen.

🔢 Loop Iterations:

i ValueCondition (i <= 5)Output
1truePrints 1
2truePrints 2
3truePrints 3
4truePrints 4
5truePrints 5
6falseLoop stops

Summary:

Above program uses a for loop to print numbers from 1 to 5, each on a new line. It’s a simple example to show how looping works in Java.

Flowchart of for Loop

Initialization → Condition → Body → Update
       ↑                              ↓
       ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ←

Use Cases of for Loop

  1. Printing numbers or patterns
  2. Repeating an operation with a counter
  3. Traversing arrays or lists (fixed size)
  4. Summing a series of numbers

Infinite for Loop

If the condition never becomes false, the loop runs forever.

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

is an example of an infinite loop in Java.

  • A for loop has no initialization, no condition, and no update.
  • Since there’s no condition to stop, it keeps running forever.
  • It will continuously print:
This is an infinite loop

until the program is manually stopped.

🛑 Use infinite loops carefully, and make sure to include a break when needed.

Decrementing for Loop

You can count backward too!

A decrementing for loop is used when you want to count backward, such as from a higher number down to a lower number.

Syntax:

for (int i = start; i >= end; i--) {
    // Code to execute
}
  • start = starting value (e.g., 5)
  • end = the limit to stop (e.g., 1)
  • i-- = decreases i by 1 after each loop

Example

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

Output

5
4
3
2
1

How It Works:

  • Starts from i = 5
  • Prints the value of i
  • Decreases i by 1 in each step
  • Stops when i becomes less than 1

Some For Loop Program to Practice

Program 1: Sum of First N Numbers Using for Loop

public class SumExample {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 10; i++) {
            sum += i;  // sum = sum + i
        }
        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 55

Program 2: Using for Loop with Arrays

public class ArrayExample {
    public static void main(String[] args) {
        int[] marks = {85, 90, 78, 92, 88};

        for (int i = 0; i < marks.length; i++) {
            System.out.println("Marks of subject " + (i + 1) + ": " + marks[i]);
        }
    }
}

Output:

Marks of subject 1: 85
Marks of subject 2: 90
Marks of subject 3: 78
Marks of subject 4: 92
Marks of subject 5: 88

Program 3: Pattern Printing Using for Loops

Let’s print a simple pyramid:

for (int i = 1; i <= 5; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 

This is an example of a nested for loop, a loop inside another loop.

Common Mistakes to Avoid

MistakeWhat Happens
Forgetting i++ or i--The loop may become infinite
Writing i = 0; i < 5; instead of ;Causes a syntax error
Misusing array indexResults in ArrayIndexOutOfBoundsException

Nested for Loops

You can put one for loop inside another. Commonly used in matrix operations and pattern printing.

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

Practice Set

  1. Write a for loop to print the even numbers between 1 and 20.
  2. Calculate the factorial of a number using a for loop.
  3. Print this pattern: 1 1 2 1 2 3 1 2 3 4
  4. Find the maximum number in an array using a for loop.
  5. Reverse an array using a for loop.

Summary

ConceptDetails
Best useWhen number of iterations is known
Syntaxfor(initialization; condition; update)
Nested loopsYes, supported
Infinite loopPossible with for(;;)
Array supportExcellent for indexing

Final Thought

The for loop in Java is a powerful and flexible tool for repeating code. Once you understand how it works with initialization, condition, and update, you can write efficient programs with ease.