Java Lesson — For Loops in Detail

A complete beginner-to-advanced lesson on repeating tasks using for loops in Java.

What this lesson covers

In this lesson, you will learn what a for loop is, why loops are useful, how the three parts of a for loop work, how Java executes a loop step by step, and how to use loops for counting, summing, tables, patterns, arrays, nested loops, and more.

We will begin from level zero, where you simply repeat something a few times, and then move toward expert-level ideas such as nested loops, break, continue, infinite loops, scope of loop variables, and choosing the right loop style.

Repetition

Run the same block many times

Counting

Perfect for known number of repetitions

Patterns

Useful for tables, stars, grids, and shapes

Control

Use break and continue to control flow

Why do we need loops?

Suppose you want to print the word Hello five times. Without a loop, you would write the same line again and again.

System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");

This works, but it is repetitive, long, and hard to maintain. A loop solves this problem by repeating a block of code automatically.

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

What is a for loop?

A for loop is used when you know how many times a block of code should run, or when the loop follows a clear counting pattern.

for (initialization; condition; update) {
    // code to repeat
}

This loop has three important parts:

Basic syntax explained

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
Part Code Meaning
Initialization int i = 1 Start with i equal to 1
Condition i <= 5 Keep looping while i is 5 or less
Update i++ Increase i by 1 after each loop

So this loop prints 1, 2, 3, 4, and 5.

Step-by-step flow of a for loop

Let us understand exactly how Java runs a for loop.

for (int i = 1; i <= 3; i++) {
    System.out.println("i = " + i);
}
  1. Java runs int i = 1 once.
  2. It checks i <= 3. This is true.
  3. It executes the body and prints i = 1.
  4. It runs i++. Now i becomes 2.
  5. It checks the condition again.
  6. The loop continues until the condition becomes false.

Printing numbers with for loops

From 1 to 10

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

From 10 down to 1

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

Even numbers from 2 to 20

for (int i = 2; i <= 20; i += 2) {
    System.out.println(i);
}

Odd numbers from 1 to 19

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

Using for loops for calculations

Sum from 1 to 5

int sum = 0;

for (int i = 1; i <= 5; i++) {
    sum = sum + i;
}

System.out.println("Sum = " + sum);

Here the loop adds each value of i into sum.

Factorial of a number

int n = 5;
int fact = 1;

for (int i = 1; i <= n; i++) {
    fact = fact * i;
}

System.out.println("Factorial = " + fact);

Count digits from repeated division idea

int num = 12345;
int count = 0;

for (; num != 0; num = num / 10) {
    count++;
}

System.out.println("Digits = " + count);

Multiplication table using for loop

int n = 7;

for (int i = 1; i <= 10; i++) {
    System.out.println(n + " x " + i + " = " + (n * i));
}

This is one of the most common and useful beginner examples.

Using a for loop with strings

You can use a for loop to go through each character of a string.

String word = "JAVA";

for (int i = 0; i < word.length(); i++) {
    System.out.println(word.charAt(i));
}

This prints J, A, V, and A one by one.

Using a for loop with arrays

int[] arr = {10, 20, 30, 40, 50};

for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

Here i is used as an index. It starts at 0 because array positions begin from 0.

Sum of array elements

int[] arr = {10, 20, 30, 40, 50};
int sum = 0;

for (int i = 0; i < arr.length; i++) {
    sum += arr[i];
}

System.out.println("Sum = " + sum);

Nested for loops

A nested for loop means a for loop inside another for loop. This is extremely useful for patterns, tables, grids, and matrix-like work.

Simple nested loop

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

For each value of i, the inner loop runs completely.

Multiplication grid

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

Pattern printing with for loops

Pattern 1: stars in one row

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

Pattern 2: square of stars

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

Pattern 3: right triangle

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

Pattern 4: number triangle

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

break in for loops

The break statement stops the loop immediately.

for (int i = 1; i <= 10; i++) {
    if (i == 6) {
        break;
    }
    System.out.println(i);
}

This prints 1 to 5 only, because the loop stops when i becomes 6.

continue in for loops

The continue statement skips the current iteration and moves to the next one.

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

This prints all numbers from 1 to 10 except 5.

Infinite for loop

If you remove the condition or make it always true, the loop may run forever.

for (;;) {
    System.out.println("Running forever");
}

This is called an infinite loop. It can be useful in special cases, but beginners should use it carefully.

Different valid forms of for loop

Initialization outside the loop

int i = 1;

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

Update inside the loop body

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

Multiple variables

for (int i = 1, j = 10; i <= 5; i++, j--) {
    System.out.println(i + " " + j);
}

Scope of loop variables

A variable declared in the loop header usually exists only inside that loop.

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

// System.out.println(i); // not allowed here

If you need the variable after the loop, declare it before the loop.

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

Common mistakes with for loops

Array mistake example

int[] arr = {10, 20, 30};

// Wrong:
// for (int i = 0; i <= arr.length; i++) {
//     System.out.println(arr[i]);
// }

This is wrong because the last valid index is arr.length - 1. The correct condition is i < arr.length.

When should you use a for loop?

If the number of repetitions is unknown and depends on a condition, a while loop may sometimes be a better fit. But for counting and indexed work, for loops are excellent.

Complete example from beginner to advanced

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

        // 2. Sum
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
        }
        System.out.println("Sum = " + sum);

        // 3. Table of 3
        for (int i = 1; i <= 10; i++) {
            System.out.println("3 x " + i + " = " + (3 * i));
        }

        // 4. Nested loop pattern
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }

        // 5. Continue example
        for (int i = 1; i <= 5; i++) {
            if (i == 3) continue;
            System.out.println("After continue check: " + i);
        }

        // 6. Break example
        for (int i = 1; i <= 10; i++) {
            if (i == 6) break;
            System.out.println("Before break point: " + i);
        }
    }
}

Assignments

Assignment 1: Print numbers from 1 to 20 using a for loop.
Assignment 2: Print numbers from 20 down to 1 using a for loop.
Assignment 3: Print all even numbers from 2 to 50.
Assignment 4: Print all odd numbers from 1 to 49.
Assignment 5: Find the sum of numbers from 1 to 100.
Assignment 6: Print the multiplication table of a user-given number.
Assignment 7: Find the factorial of a number using a for loop.
Assignment 8: Print a square pattern of stars of size 5 by 5.
Assignment 9: Print a triangle pattern using nested for loops.
Assignment 10: Use break to stop a loop at a chosen point and continue to skip one chosen value.

Interactive MCQ Quiz

Choose one answer for each question and click Check Answers.

Total Questions: 0

0 / 0

Your result will appear here.

Quick revision