Software & Finance





Java - Difference Between for, while and do while loop





The main difference between for loop, while loop, and do while loop is

  • While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.
  • do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false.
  • for loop is similar to while loop except that
    • initialization statement, usually the counter variable initialization
    • a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement
    The following sample code explains all 3 different loops:

 

 

Source Code


import java.lang.*;

import java.util.*;

import java.io.*;

 

 

class LoopsDifference

{

   public static void main(String[] args)

   {    

      int MAX = 5;

      for (int i = 0; i < MAX; i++)

      {

         System.out.format("For Loop : %d\n", i);

      }

 

      int j = 0;

      while (j < MAX)

      {

         System.out.format("While Loop : %d\n", j);

         j++;

      }

 

      int k = 0;

      do

      {

         System.out.format("Do While Loop : %d\n", k);

         k++;

      } while (k < MAX);

   }

}

Output


For Loop : 0

For Loop : 1

For Loop : 2

For Loop : 3

For Loop : 4

 

While Loop : 0

While Loop : 1

While Loop : 2

While Loop : 3

While Loop : 4

 

Do While Loop : 0

Do While Loop : 1

Do While Loop : 2

Do While Loop : 3

Do While Loop : 4

 

Press any key to continue . . .