Java Nested Loops with Examples



Loops in Java are called control statements because they decide the flow of execution of a program based on some condition. Java allows the nesting of loops.

When we put a loop within another loop, then we call it a nested loop. Nested loops are used when we need to iterate through a matrix array and when we need to do any pattern-based questions.

In this article, we are going to learn about Java nested loops with examples.

Nested Loops in Java

We can create nested loops for the following control statements in Java:

Let's discuss these nested loops with some examples -

Nested for Loop

The for loop is the most used control statement in any programming language because it is easy to understand and implement.

Loop iterate till the given condition is true. A nested for loop refers to a for loop within another for loop.

Syntax

for (initial expression; conditional expression; increment/decrement expression){
   // code to be executed
   for (initial expression; conditional expression; increment/decrement expression) {
      // code to be executed
   }
}

Where,

  • initial expression: Executed once when the loop begins.
  • conditional expression: The code will be executed till the conditional expression is true. 
  • increment/decrement expression: To increment/decrement the loop variable.

Example

The following program will perform the addition of two matrices using a nested for loop.

The first two for loops will run 4 times, and during each iteration values of mtr1 and mtr2 will get stored in the third matrix add. The last two for loops will print the result on the screen.

public class Main{
   public static void main(String args[]){
      int mtr1[][] = {{2,7},
      {9,2}};
      int mtr2[][] = {{6,3},
      {5,1}};
      int add[][] = new int[2][2];
      // Nested for loop
      for (int i= 0 ; i < 2 ; i++ ){ 
         for (int j= 0 ; j < 2 ;j++ ){
            add[i][j] = mtr1[i][j] + mtr2[i][j]; 
            // Performing addition
         }
      }
      System.out.println("Sum of given two matrices =");
      // Nested for loop to print the resulted matrix
      for (int i= 0 ; i < 2 ; i++ ){
         for (int j= 0 ; j < 2 ;j++ ){
            System.out.print(add[i][j]+"\t");
         }
         System.out.println();
      }
   }
}

On executing the above code, you will get the following result:

Sum of given two matrices =
8   10
14   3

Nested while Loop

The while loop is an entry control loop where the condition is checked before moving to the loop's body. The nested while loop refers to a while loop inside another while loop.

Syntax

while (conditional expression) {
   // code will be executed till the conditional expression is true
   while (conditional expression) {
      // code will be executed till the conditional expression is true
      increment/decrement expression; 
      // to increment/decrement loop variable
   }
   increment/decrement expression; 
   // to increment/decrement loop variable
}

Example

The following program will perform the addition of two matrices using a nested while loop.

public class Main{
   public static void main(String args[]){
      int mtr1[][] = {{2,7},{9,2}};
      int mtr2[][] = {{6,3},{5,1}};
      int add[][] = new int[2][2];
      int i=0;
      // Nested while loop to perform addition
      while(i<2){
         int j=0;
         while(j<2){
            add[i][j] = mtr1[i][j] + mtr2[i][j]; 
            j++;
         }
         i++;
      }
      System.out.println("Sum of given two matrices =");
      i=0;
      // Nested while loop to print result
      while(i<2){
         int j=0;
         while(j<2){
            System.out.print(add[i][j]+"\t");
            j++;
         }
         System.out.println();
         i++;
      }
   }
}

The above code will print the sum of two matrices.

Sum of given two matrices =
8    10
14    3

Nested do while Loop

The do while loop is an exit control loop, where the loop's body gets executed before checking the given test condition.

The nested do while loop can also be created by using a do-while loop inside another do-while loop.

Syntax

do{
    //statement for the outer loop
    do{
      //statement for the inner loop inner
    }while(condition B);
}while(condition A)

Example

This Java program uses nested do-while loops to print a grid of asterisks (*).

public class Main {
    public static void main(String[] args) {
	    int rows = 3;
	    int cols = 4;
	    int i = 1;
	    do {
                    int j = 1;
	        do {
	              System.out.print("* ");
		      j++;
		}
		while (j <= cols);
		System.out.println();
	        i++;
	    }
        while (i <= rows);
    }
}

Output:

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

Nested for each Loop

A for each loop is a special repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.

The nested for each loop refers to using a for each loop inside another for each loop.

Syntax

for (Type[] arrayElement : outerArray) {
    for (Type element : arrayElement) {
        // Inner loop statements
    }
}

Example

This Java program demonstrates the use of nested for-each loops to iterate through a 2D array of strings and print its elements.

public class NestedForEachExample3 {
   public static void main(String[] args) {
      String[][] array = {
         {"apple", "banana", "cherry"},
         {"dog", "elephant", "frog"},
         {"grape", "honey", "ice"}
      };

      for (String[] row : array) {
         for (String element : row) {
            System.out.print(element + " ");
         }
         System.out.println();
      }
   }
}

The above code will print the elements of the String array:

apple banana cherry 
dog elephant frog 
grape honey ice
Updated on: 2025-06-18T19:09:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements