Nested Loops
Nested loops in Java are loops inside another loop. They are used when a task requires repeated execution within repeated execution, such as matrix processing, pattern printing, and multi-dimensional data handling. This concept is essential for logic building and interviews.
What Are Nested Loops?
- A loop placed inside another loop
- Inner loop executes completely for each outer loop iteration
- Can be any combination of for, while, or do-while
Basic Structure
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println(i + "," + j);
}
}
Execution Flow (Important)
- Outer loop runs first
- For each iteration of outer loop, inner loop runs fully
- Total iterations = (outer loop count × inner loop count)
Example with Execution Count
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
* *
* *
* *
Total executions: Outer = 3, Inner = 2 → 6 executions
Nested for Loop (Most Common)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i + j + " ");
}
System.out.println();
}
Nested while Loop
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 2) {
System.out.println(i + "," + j);
j++;
}
i++;
}
Mixed Nested Loops
for (int i = 1; i <= 2; i++) {
int j = 1;
while (j <= 3) {
System.out.println(i + "," + j);
j++;
}
}
Nested Loops with break
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break;
}
System.out.println(i + "," + j);
}
}
Nested Loops with Labeled break
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outer;
}
System.out.println(i + "," + j);
}
}
Nested Loops with continue
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
System.out.println(i + "," + j);
}
}
Common Use Cases
- Pattern printing
- Matrix operations
- Tables and grids
- Searching in 2D data
- Combinational logic
Performance Consideration (Important)
- Time complexity increases with nesting
- Example: O(n²) for two nested loops
Best Practice: Avoid unnecessary nesting in large datasets.
Common Beginner Mistakes
- Infinite loops due to incorrect inner loop update
- Confusing loop variables
- Excessive nesting reducing readability
- Forgetting braces {}
Interview-Ready Answers
Short Answer
Nested loops are loops placed inside another loop, where the inner loop executes fully for each iteration of the outer loop.
Detailed Answer
In Java, nested loops allow repetitive processing within repeated execution. They are commonly used for matrix handling, pattern generation, and multi-dimensional data processing. However, excessive nesting can impact performance.
Key Takeaway
Nested loops are powerful for multi-level iteration, but should be used carefully to maintain readability and performance.