Nested Loops in Java
A nested loop is simply a loop written inside the body of another loop, and it's the standard way to work across two dimensions at once — rows and columns in a grid, or every pair from two separate lists. The outer loop runs once per row, so to speak, and for every single one of those outer iterations, the entire inner loop runs completely from start to finish before the outer loop moves on to its next iteration.
Total iteration count multiplies rather than adds — an outer loop running 3 times paired with an inner loop running 4 times each runs the inner body 12 times total, not 7. That matters directly for reasoning about a nested loop's performance as the inputs grow.
The basic shape
One loop's body contains an entirely separate loop, with its own counter and its own condition.
Outer loop controls repetition of the whole inner loop
Each single iteration of the outer loop runs the complete inner loop from start to finish.
Iteration counts multiply
An outer loop of size m paired with an inner loop of size n runs the innermost body m times n times in total.
A natural fit for grids
Nested loops are the standard way to visit every cell of a two-dimensional structure, row by row and column by column.
Watch performance as inputs grow
Because counts multiply, a nested loop over two inputs of size n each does n times n work, which grows quickly as n increases.
public class NestedLoopDemo { public static void main(String[] args) { for (int row = 1; row <= 2; row++) { for (int col = 1; col <= 3; col++) { System.out.println("Row " + row + ", Col " + col); } } }}Work scales with the product of the two loop bounds, not their sum — doubling either one roughly doubles the total number of times the inner body runs.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.