John Selawsky
Senior Java Developer and Tutor at LearningTree

Java Nested Loops

Published in the Java Developer group
Java, like most other programming languages, supports nested loops. This means just a loop within a loop. In this article, we are going to find out about how to work with nested loops in Java.

Java nested loops

A loop is called nested if it is placed inside another loop. On the first pass, the outer loop calls the inner loop, which runs to completion, after which control is transferred to the body of the outer loop. On the second pass, the outer loop calls the inner one again. And so on until the outer loop ends. There are four types of loops in Java:
  • for loop

  • while loop

  • do...while loop

  • for-each loop

All of them support nested loops. Nested-loop constructs are used when two conditions must be met, one depending on the other. For example, if you need to display a two-dimensional matrix, a semi-pyramid or a multiplication table.

How Java nested loops work

Probably the most used loop in Java is for, in large part because it is quite versatile and the code with it is quite easy to read. Here is the general syntax for nested for loop:

// outer loop
for (initialization; condition; increment) {
  //write here your code 

  //nested loop
  for(initialization; condition; increment) {
    //write here your code
  }
..
}
How does he work? The outer loop starts. Then the nested for loop starts the work and goes through its index until the condition is met, and again passes the work to the outer loop, and this happens until the condition of the outer loop is met. Sounds a little tricky, doesn't it? Well, It will be much easier to understand with a specific example, so let's move on to it.

Nested for loop code example

Here is one classic example. Let’s print out a half pyramid using two for loops. One of them is nested.

public class NestedLoopsDemo1 {

   public static void main(String[] args) {

       for (int i = 0; i < 10; i++) {
           for (int j = 0; j<=i;  j++)
               System.out.print("*");
           System.out.println();
       }
      
   }
}
The output is:
* ** *** **** ***** ****** ******* ******** ********* **********

Nested while loop code example


public class NestedLoopsDemo2 {

   public static void main(String[] args) {

       int i = 0;
       while (i < 10) {
           int j = 0;
           while (j <= i) {
               System.out.print("*");
               j++;
           }
           System.out.println();
           i++;

       }
   }
}
The output is just the same as in the previous example:
* ** *** **** ***** ****** ******* ******** ********* **********
The do...while loop is similar to while loop. The main difference is, that the body of do...while loop is executed once before the expression checking.

Nested foreach loops code example

for-each loop can be nested like usual for loop. Here is the example for nested for-each loop which iterates 2-dimensional array.

public class NestedLoops2 {

       public static void main(String[] args)
       {
           int[][] mainArray = { {5, 4, 3, 2, 1}, {7, 8, 9, 10, 11} };

           for (int[] myArray : mainArray)
           {
               for (int i : myArray)
               {
                   System.out.print(i+" ");
               }
               System.out.println("");
           }
       }
}
The output is:
5 4 3 2 1 7 8 9 10 11

Mixed for and while loop example

Sometimes we can nest different types of loops inside each other. For example, for inside while or for inside for-each. However, it’s not the best programming practice. Such constructs significantly impair the readability of the code. So professional programmers try not to mix one with the other. Well, they do, but only if it’s really needed. And one more little rule: if you are choosing between while and for, use for where possible. Nevertheless, here we are going to have an example of using a for loop inside the while. Let's build our semi-pyramid again.

public class NestedLoopsDemo2 {

   public static void main(String[] args) {
       int i = 0;
       while (i < 10) {
           for (int j = 0; j <= i; j++) {
               System.out.print("*");
           }
           System.out.println();
           i++;

       }
   }
}
The output is without surprises:
* ** *** **** ***** ****** ******* ******** ********* **********
Java Nested Loops - 1
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION