Understanding do-while loop in java language

A do while loop in java is just like a while loop but the main difference between while and do-while loop is that do-while loop is guaranteed to execute the loop at least one time.

Syntax for Java do-while

Below is given the syntax of the do-while loop in Java:

do {
   // Statements will be here
}while(Boolean_expression);

In the above code, you can notice that the Boolean expression appears at the end of the loop, so the statements inside the loop will execute at least one time before the Boolean expression execute.

If the Boolean expression becomes true, the control will then jump again to the loop statements in the loop and it will execute again. The same process will occur repeatedly until it returns false.

Java do-while loop example with code

Below is the given example which you can run on your machine:



public class Dowhile {

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

      do {
         System.out.println( x );
         x++;
         
      }while( x < 10 );
   }
}

You can see that it is just a simple demo example code so that you can understand it easily. The code should print x value until the expression x<10 become true. After it returns x value 10 the loop expression should be stopped.

Now compile and then run the above code and what will you see after you run the code? You will see the result output that is shown below:

0
1
2
3
4
5
6
7
8
9

The loop has printed the value of x repeatedly until it value becomes less than 10. When it see the value of x is 10, it will take the expression as false and stop executing the code.

Leave a Reply

Your email address will not be published. Required fields are marked *