Table of contents
1.
Introduction
2.
Types of Nested Loops
3.
Syntax 
3.1.
Basic Structure of Nested For Loops
3.2.
Basic Structure of Nested While Loops
3.3.
Basic Structure of Nested Do-While Loops
4.
Examples of Nested Loops in Java
4.1.
Example 1: Nested For Loop
4.2.
Java
4.3.
Example 2: Nested While Loop
4.4.
Java
4.5.
Example 3: Nested Do-While Loop
4.6.
Java
5.
Common Use Cases of Nested Loops
5.1.
Printing Patterns
5.2.
Java
5.3.
Iterating Over Multi-Dimensional Arrays
5.4.
Java
6.
Frequently Asked Questions
6.1.
What are nested loops in Java?
6.2.
When should nested loops be used?
6.3.
How to optimize nested loops?
7.
Conclusion
Last Updated: Jul 14, 2024
Easy

Nested Loops in Java

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, loops are used to execute a block of code repeatedly. Sometimes, you may need to place one loop inside another loop. This is known as nesting loops. 

Nested Loops in Java

Nested loops are useful when you need to perform a series of operations within a multi-dimensional data structure or create complex patterns.

Types of Nested Loops

  1. Nested For Loops
     
  2. Nested While Loops
     
  3. Nested Do-While Loops

Syntax 

Basic Structure of Nested For Loops

for (initialization; condition; update) {
    for (initialization; condition; update) {
        // Inner loop code
    }
    // Outer loop code
}

Basic Structure of Nested While Loops

while (condition) {
    while (condition) {
        // Inner loop code
    }
    // Outer loop code
}

Basic Structure of Nested Do-While Loops

do {
    do {
        // Inner loop code
    } while (condition);
    // Outer loop code
} while (condition);

Examples of Nested Loops in Java

Example 1: Nested For Loop

  • Java

Java

public class NestedForLoopExample {

   public static void main(String[] args) {

       for (int i = 1; i <= 3; i++) {

           for (int j = 1; j <= 3; j++) {

               System.out.println("i: " + i + ", j: " + j);

           }

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output:

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3


Explanation:

  • The outer loop runs 3 times.
     
  • For each iteration of the outer loop, the inner loop runs 3 times.

Example 2: Nested While Loop

  • Java

Java

public class NestedWhileLoopExample {

   public static void main(String[] args) {

       int i = 1;

       while (i <= 3) {

           int j = 1;

           while (j <= 3) {

               System.out.println("i: " + i + ", j: " + j);

               j++;

           }

           i++;

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3


Explanation

  • The outer loop uses a while loop to run 3 times.
     
  • The inner loop also uses a while loop to run 3 times for each iteration of the outer loop.

Example 3: Nested Do-While Loop

  • Java

Java

public class NestedDoWhileLoopExample {

   public static void main(String[] args) {

       int i = 1;

       do {

           int j = 1;

           do {

               System.out.println("i: " + i + ", j: " + j);

               j++;

           } while (j <= 3);

           i++;

       } while (i <= 3);

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3


Explanation

  • The outer loop uses a do-while loop to run 3 times.
     
  • The inner loop also uses a do-while loop to run 3 times for each iteration of the outer loop.

Common Use Cases of Nested Loops

Printing Patterns

Nested loops are often used to print patterns. For example, a simple star pattern can be printed using nested loops.

  • Java

Java

public class StarPattern {

   public static void main(String[] args) {

       for (int i = 1; i <= 5; i++) {

           for (int j = 1; j <= i; j++) {

               System.out.print("*");

           }

           System.out.println();

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

*
**
***
****
*****

Iterating Over Multi-Dimensional Arrays

Nested loops are ideal for iterating over multi-dimensional arrays.

  • Java

Java

public class MultiDimensionalArray {

   public static void main(String[] args) {

       int[][] array = {

           {1, 2, 3},

           {4, 5, 6},

           {7, 8, 9}

       };

       for (int i = 0; i < array.length; i++) {

           for (int j = 0; j < array[i].length; j++) {

               System.out.print(array[i][j] + " ");

           }

           System.out.println();

       }

   }

}
You can also try this code with Online Java Compiler
Run Code


Output

1 2 3
4 5 6
7 8 9

Frequently Asked Questions

What are nested loops in Java?

Nested loops are loops inside another loop, used for iterating over multi-dimensional data or creating patterns.

When should nested loops be used?

Use nested loops when you need to perform repeated actions on multi-dimensional data or when implementing complex algorithms.

How to optimize nested loops?

Optimize by minimizing iterations, breaking down loops into methods, and ensuring loops are necessary.

Conclusion

Nested loops in Java are powerful for handling complex data structures and algorithms. Understanding their syntax, use cases, and best practices ensures you can leverage them effectively in your programs. By following performance considerations and avoiding common pitfalls, you can write efficient and readable code using nested loops.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass