Java Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

In Java, nested loops allow you to place one loop inside another. The “inner loop” executes once for every iteration of the “outer loop.”

The “inner loop” will be executed one time for each iteration of the “outer loop”:



Example

In this example, the outer loop runs twice, and for each iteration of the outer loop, the inner loop runs three times. Thus, the inner loop executes a total of 6 times (2 outer iterations * 3 inner iterations).

// Outer loop
for (int outer = 1; outer <= 2; outer++) {
  System.out.println("Outer loop: " + outer); // Executes 2 times

  // Inner loop
  for (int inner = 1; inner <= 3; inner++) {
    System.out.println(" Inner loop: " + inner); // Executes 6 times (2 * 3)
  }
}

Scroll to Top