Nested For Loop in Java | Example Program

Nested for loop in Java means one for statement inside another for statement. In other words, a for loop nested inside another for loop is called nested for loops.

A nested for loops consist of an outer for loop and one or more inner for loops. Each time the outer for loop is repeated, the inner for loop re-enters and starts a new execution.

That is, each time the control will enter inside the inner for loop when the outer for loop is repeated.

The general syntax for nested for loops in Java is as follows:

// Outer for loop.
for ( initialization; test-condition; increment ) 
{
// Inner for loop.
   for ( initialization; test-condition; increment ) 
   {
    // statement of inner loop
   }
 // statement of outer loop
}

Let’s understand it with the help of an example.

for(int i = 1; i <= 3; i++){
  statement1; // This statement will be executed 3 times by changing i values from 1 to 3.
}
for(int j = 1; j <= 4; j++){
  statement2; // This statements will be executed 4 times by changing j value from 1 to 4.
}

If we write first for loop inside the second for loop, it will look like this:

for(int i = 1; i <= 3; i++)
{
  statement1; // will be executed 3 times.
  for(int j = 1; j <= 4; j++)
  {
    statement2; // will be executed 12 (3 * 4) times.
  }
}

a) In this example, when i = 1, execution will start from the outer for loop and statement1 will be executed once.

b) Now, the control of execution enters into the inner for loop. Since the control variable j is initially set to 1, statement2 will be executed once.

c) After this execution, the value of j will be 2 due to increment by 1. Then, statement2 will be executed once again.

d) Like this, the inner for loop will be executed 4 times with changing j values from 1 to 4. This means that statement2 will be executed 4 times in the first execution of outer for loop.

e) When the execution of inner for loop is completed, the control of execution goes to the outer for loop. Now, the value of i will be 2 due to increment by 1.

This time, the control of execution again enters into the inner for loop and statement2 will execute 4 times.

f) Then, the control again goes to outer for loop and the value of i will be set to 3. Again the inner for loop is executed 4 times.

This means that the values of i and j will change like this:

  • i = 1,  j = 1, 2, 3, 4
  • i = 2,  j = 1, 2, 3, 4
  • i = 3,  j = 1, 2, 3, 4

In the above sequence, the outer for loop is executed a total of 3 times, and hence statement1 inside the loop body will be executed 3 times.

The inner for loop is executed 4 times for each i value and hence statements2 inside the loop body will be executed 12 times.

In the same way, we can also nest a while loop or a do-while loop inside a for loop and vice versa. These are called nested loops in Java.
Next ⇒ For each loop in Java

⇐ Prev Next ⇒