Java Nested Loops: Organize Repetitive Tasks with Multiple Loops
Learn how to use nested loops in Java, where one loop is placed inside another. Understand how the inner loop executes for each iteration of the outer loop, enabling you to handle more complex repetitive tasks efficiently in your Java programs.
Java Nested Loops
You can place a loop inside another loop. This is called a nested loop.
The "inner loop" runs once for each iteration of the "outer loop":
Example
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
Output
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3