Java Nested Loops
A nested loop is simply a loop placed inside another loop. The inner loop runs all the way through for every single pass of the outer loop, which lets you work with grids, tables, and combinations of things.
How nesting works
Picture the outer loop as rows and the inner loop as columns. For each row, the inner loop runs from start to finish before the outer loop moves on to the next row. That is why the total number of inner passes is the outer count multiplied by the inner count.
An outer and inner loop together
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 2; col++) {
System.out.println("Row " + row + ", Col " + col);
}
}
// Output:
// Row 1, Col 1
// Row 1, Col 2
// Row 2, Col 1
// Row 2, Col 2
// Row 3, Col 1
// Row 3, Col 2The outer loop ran 3 times and the inner loop ran 2 times per outer pass, giving 3 times 2, which is 6 lines of output in total.
Building a pattern
Nested loops are great for drawing shapes and grids. Here the inner loop prints a number of stars that grows with each row, building a simple triangle.
A star triangle
for (int row = 1; row <= 4; row++) {
String line = "";
for (int star = 1; star <= row; star++) {
line += "*";
}
System.out.println(line);
}
// Output:
// *
// **
// ***
// ****- The inner loop completes fully for each pass of the outer loop.
- Total inner runs equal the outer count times the inner count.
- Deep nesting can get slow, so keep an eye on how many total passes you create.
- Use clear, distinct variable names for each level.