Java Lesson — Nested Loops in Detail

A complete lesson on loops inside loops, from level zero to advanced pattern building.

What this lesson covers

In this lesson, you will learn what a nested loop is, how the outer loop and inner loop work together, how to trace nested loop execution, and how nested loops are used for tables, patterns, grids, arrays, and matrix-like logic.

We will begin with the simple idea of one loop inside another, then move to pattern printing, rectangular grids, multiplication tables, searching combinations, break and continue in nested loops, and best practices for writing clean nested loop code.

Outer Loop

Controls rows or major repetitions

Inner Loop

Runs fully for each outer step

Patterns

Stars, numbers, grids, shapes

Tables

Useful for multiplication and 2D work

What is a nested loop?

A nested loop means one loop written inside another loop. The outer loop runs one time, and for each of its iterations, the inner loop runs completely.

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

Here, the outer loop uses i and the inner loop uses j. For each value of i, the inner loop starts again from its beginning.

How nested loops execute

Let us trace this code carefully:

for (int i = 1; i <= 2; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.println("i = " + i + ", j = " + j);
    }
}
  1. The outer loop starts with i = 1.
  2. Then the inner loop runs with j = 1, j = 2, and j = 3.
  3. After the inner loop finishes, the outer loop changes i to 2.
  4. Then the inner loop starts again from j = 1.
  5. This continues until the outer loop condition becomes false.

So the inner loop does not continue from its old value. It starts fresh every time the outer loop repeats.

Output of a basic nested loop

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

Notice that for every outer loop value, the inner loop runs all of its values.

Rows and columns thinking

Nested loops are often understood in terms of rows and columns.

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 4; col++) {
        System.out.print("* ");
    }
    System.out.println();
}

This prints 3 rows, and in each row it prints 4 stars.

Printing a rectangle

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 5; col++) {
        System.out.print("* ");
    }
    System.out.println();
}
* * * * *
* * * * *
* * * * *

The outer loop controls the number of lines. The inner loop controls how many symbols appear in each line.

Printing a square

for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= 4; col++) {
        System.out.print("# ");
    }
    System.out.println();
}

When rows and columns are equal, you get a square shape.

Printing a right triangle

In this pattern, the number of columns depends on the current row.

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

Here, the inner loop limit is not a fixed number. It depends on row.

Printing an inverted triangle

for (int row = 5; row >= 1; row--) {
    for (int col = 1; col <= row; col++) {
        System.out.print("* ");
    }
    System.out.println();
}
* * * * *
* * * *
* * *
* *
*

Number patterns with nested loops

Pattern 1

for (int row = 1; row <= 5; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print(col + " ");
    }
    System.out.println();
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Pattern 2

for (int row = 1; row <= 5; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print(row + " ");
    }
    System.out.println();
}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Multiplication table grid

Nested loops are very useful for multiplication tables.

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

This creates a 5 by 5 multiplication grid.

Nested loops with arrays

Nested loops are very common when working with 2D arrays or matrix-like data.

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        System.out.print(matrix[row][col] + " ");
    }
    System.out.println();
}

The outer loop moves through rows, and the inner loop moves through the elements inside one row.

Searching pairs with nested loops

Sometimes you want to check all possible pairs of values. Nested loops are perfect for that.

int[] arr = {2, 4, 6, 8};

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

This prints every unique pair from the array.

break inside nested loops

A break only stops the loop in which it appears.

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

Here, the inner loop stops when j == 3, but the outer loop continues.

continue inside nested loops

A continue skips the current iteration of the loop in which it appears.

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

This skips the inner loop step whenever j == 2.

Using labels with break

Java also supports labeled breaks, which can stop an outer loop from inside an inner loop.

outerLoop:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 4; j++) {
        if (i == 2 && j == 3) {
            break outerLoop;
        }
        System.out.println("i = " + i + ", j = " + j);
    }
}

This breaks out of both loops together. It is powerful, but should be used carefully.

Common mistakes in nested loops

Wrong pattern example

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 4; col++) {
        System.out.print("* ");
    }
}

This prints all stars in one long line because there is no System.out.println() after the inner loop.

Time complexity idea

A single loop may run n times. A nested loop may run about n × n times in many cases. That is why nested loops can be much more expensive than a single loop.

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        // work
    }
}

This kind of pattern is often called O(n²) time.

Complete example

public class Main {
    public static void main(String[] args) {
        // Rectangle
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 5; col++) {
                System.out.print("* ");
            }
            System.out.println();
        }

        System.out.println();

        // Triangle
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(row + " ");
            }
            System.out.println();
        }

        System.out.println();

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

Assignments

Assignment 1: Print a rectangle of stars with 4 rows and 6 columns.
Assignment 2: Print a square pattern of size 5 using nested loops.
Assignment 3: Print a right triangle of stars with 5 rows.
Assignment 4: Print an inverted right triangle of stars.
Assignment 5: Print the pattern 1, then 1 2, then 1 2 3, and so on up to 5 rows.
Assignment 6: Print a 10 by 10 multiplication grid.
Assignment 7: Take a 2D array and print all elements row by row.
Assignment 8: Print all unique pairs from an array of numbers.
Assignment 9: Use break inside the inner loop and observe what happens.
Assignment 10: Use a labeled break to stop both loops together.

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