Website For Developers

Nested Loop in Java



Syntax

for (initialization; condition/check; increment/decrement) {
// outer-for loop body
for (initialization; condition/check; increment/decrement) {
// inner-for loop body
}
}


Example of nested loop in Java

public class NestedForLoop {

   public static void main(String[] args) {
     for (int i = 1; i < 3; i++) {
       //body of outer loop starts
       for (int j = 1; j <= 3; j++) {
         //body of inner loop starts
         System.out.println( "Outer loop value is: "+i+"\t Inner loop value is: "+j);
       }//body of inner loop ends
     }//body of outer loop ends
   }
}

Output

Outer loop value is: 1   Inner loop value is: 1
Outer loop value is: 1   Inner loop value is: 2
Outer loop value is: 1   Inner loop value is: 3
Outer loop value is: 2   Inner loop value is: 1
Outer loop value is: 2   Inner loop value is: 2
Outer loop value is: 2   Inner loop value is: 3

How above example works?