Java Loops

Java Loops are the keywords that are used to repeat lines of code multiple times. With Java loops same piece of code can be repeated multiple times without writing the same lines of code again and again.

In programming, quite often there comes a situation when a programmer needs to repeat a piece of code multiple times.

Why is Repetition Needed?

Repetition provides following purposes:

  • Duplication
  • Taking input, sum, and average of multiple numbers using a limited number of variables

For example, if we want to add five numbers we may have two different algorithms:

  • Declare a variable for each number, input the numbers and add the variables together
  • A single variable that contains the sum of the numbers

In first case we have to use five variables and then add them up while in second case we just need to take one variable and create a loop which will run five times and we will get more efficient program.

In this scenario, the best practice is to avoid writing the same lines of code again and again. To handle this situation, Java programming language has loops.

Java Loops

A Java loop statement allows user to execute a statement or group of statements multiple times. For instance, if a programmer needs to print a sentence 10 times then instead of writing print() statement 10 times, the programmer can use loops. The below diagram shows the structure of Java Loops.

Java Loop
Java Loop Structure

There are three basic types of loops in Java Programming Language:

  • while Loop
  • for Loop
  • do…while Loop

The detail description of these loops is given in the sections below:

while loop

The while loop uses while keyword. It keeps executing the piece of code while the defined condition is true. It stops execution when the condition becomes false. The syntax of writing while loop is:

Here, the condition can be any Boolean expression. The curly braces contain piece of code. The piece of code can be a single statement or multiple statements. Note that if while condition is never true then the code body inside the while loop will never be executed.

The program checks if the condition evaluates to true and then executes the code in loop body. It again reevaluates the condition and keeps executing the code within the loop until the condition is no longer true. When the condition becomes false, the program exits the loop.

The below example shows the demonstration of while loop inside the Java code:

public class Example {

   public static void main(String args[]) {
      int i = 0;

      while( i < 10 ) {
         System.out.print("value of i is : " + i );
         i++;
         System.out.print("\n");
      }
   }
}

The above code will print the value of i and will keep on adding 1 in it until it is equal to 10. When the value of variable i becomes equal to 10, the while condition will become false and loop will be exited. The initial value of variable i is 0 so it will execute the condition in the loop 11 times. It will print the value of i 10 times. But O\on 11th time, the condition becomes false so loop body is not executed. The output of the above code after compilation is:

for loop

The for loop uses for keyword and it has three control statements. for loop executes piece of code multiple times depending on the value of control variable. It executes the code statement for known number of times. The scenarios where programmer knows exactly how many times the code must be executed, for loop is used. The syntax of for loop is:

Here, in initial statement, the loop control variable is initialized. In the loop condition, Boolean expression is written and in the update statement usually increment or decrement statement is written. The update statement assigns a new value to the loop control variable. These conditions are written in parenthesis () and each condition is separated by another using semi colons ;. The curly braces {} contain the code body that needs to executed. The for loop executes in the following sequence:

  1. First, the compiler executes the initial statement
  2. In the second step, the compiler validates the loop condition
  3. If the loop condition is true, the compiler executes the block of code inside the curly braces
  4. Then the compiler executes the update statement
  5. The compiler repeats steps 2,3,4 until the loop condition evaluates to false.

Here is an example, that shows the demonstration of for loop:

public class Example {

   public static void main(String args[]) {

      for(int i = 0; i < 10; ++i) {
         System.out.print("Value of i is: " + i );
         System.out.print("\n");
      }
   }
}

The output of the above code after compilation is: Java Loop

Nested for loop

A for loop inside the body of another for loop make nested for loop. The syntax of writing nested for loop is:

The below example demonstrates the working of nested for loop through code.

// The file name is Example.java
class Example {
  public static void main(String[] args) {

    int minutes = 2;
    int seconds = 3;

    // outer loop prints minutes
    for (int i = 1; i <= minutes; ++i) {
      System.out.println("Minute: " + i);

      // inner loop prints seconds
      for (int j = 1; j <= seconds; ++j) {
        System.out.println("  Second: " + j);
      }
    }
  }
}

The output of the above code after compilation and execution is:

do…while loop

The do…while loop uses do and while keywords. It works similar to the while loop. The difference between while and do…while loops is their order of execution. In do…while loop the compiler first executes the body of the loop and then checks the loop condition. The do…while loop has an exit condition and always iterates at least once unlike for and while loops. The below diagram helps explain the working of do…while loop.

Java Loop
do…while Java Loop Structure

The syntax of do…while loop is:

Here, the curly braces {} contains the code statements to be executed. The parenthesis () contain the condition to be verified. The condition can be a Boolean expression. The sequence of execution of while loop is:

  • First, the compiler executes the code in the loop body regardless of the loop condition.
  • It then verifies the condition, if it is true then it executes the code in loop body again and if it is false, the compiler exits the loop.
  • The compiler repeats the above steps until the loop condition becomes false.

The below example shows the working of do…while loop in Java code.

public class Example {

   public static void main(String args[]) {
      int i = 0;

      do {
         System.out.print("Value of i is : " + i );
         ++i;
         System.out.print("\n");
      }while( i < 10 );
   }
}

The output of the above code after compilation is: Java Loop

In the above example, if we change the initial value of variable i to 10 from 0, then the condition in the while loop is not satisfied but the code in the while loop will be executed once.

public class Example {

   public static void main(String args[]) {
      int i = 10;

      do {
         System.out.print("Value of i is : " + i );
         ++i;
         System.out.print("\n");
      }while( i < 10 );
   }
}

The output of the above code after compilation is: Java Loop