W3docs

Java Nested Loops

Combine loops inside loops in Java to process multi-dimensional data, with patterns for matrices and grids.

A nested loop is a loop inside another loop. The inner loop runs to completion on each pass of the outer loop, so the body executes outer × inner times. This is the basic shape for every problem involving rows and columns, pairs, or multi-dimensional data.

This chapter assumes you know the basic loop forms — the for loop and the while loop. Any loop can nest inside any other; the examples below use for because it's the most common, but the rule is the same for while and for-each.

Two for loops

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

Output:

1,1
1,2
1,3
2,1
2,2
2,3
3,1
3,2
3,3

For each value of i, the inner loop runs through j from 1 to 3 before i advances. Note that j is re-initialized to 1 on every outer pass — the inner loop starts fresh each time the outer loop repeats. Keep the loop variables distinct (i and j here); reusing the same name inside both loops is a common source of bugs.

Walking a 2D array

The textbook use of nested loops is iterating over a matrix:

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

for (int r = 0; r < grid.length; r++) {
  for (int c = 0; c < grid[r].length; c++) {
    System.out.print(grid[r][c] + " ");
  }
  System.out.println();
}

Each row of the grid is itself an array; the outer loop iterates rows, the inner loop iterates the cells in each row. The for-each form is even cleaner when you don't need the indices:

for (int[] row : grid) {
  for (int cell : row) {
    System.out.print(cell + " ");
  }
  System.out.println();
}

Printing patterns

Nested loops are a classic exercise for printing patterns. A triangle of stars:

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

Output:

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

The inner loop's count depends on the outer loop's variable — a powerful pattern that shows up constantly.

Watch the complexity

A single loop over n items runs n times. A loop nested inside it runs n × n = n² times. Three nested loops run times. For small n this doesn't matter; for large n it matters a lot:

n
101001,000
10010,0001,000,000
1,0001,000,0001,000,000,000

If your nested loop is over a large data set, ask whether you actually need the inner loop. A HashMap lookup often replaces an inner search loop and changes O(n²) into O(n).

break and continue only affect the inner loop

We saw this in break and continue: without a label, both apply only to the innermost loop. To break out of the outer loop or skip its iteration from inside the inner one, use a labeled break or continue — see labeled statements.

A worked example

java— editable, runs on the server

What's next

When you need to break or continue an outer loop from inside an inner one, labeled statements give you a clean way to do it.

Practice

Practice
How many times does the System.out.println run in: for (int i = 0; i < 4; i++) for (int j = 0; j < 3; j++) System.out.println(i+','+j);
How many times does the System.out.println run in: for (int i = 0; i < 4; i++) for (int j = 0; j < 3; j++) System.out.println(i+','+j);
Was this page helpful?