do-while Loop in Java


If the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional expression is false, to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Fortunately, java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. its general form is

do
{
  //body of the loop
}
while(condition);

do-while Loop Example 1

In the following example, the condition applied inside the do-while loop is that the value of 'i' will continue until the value is greater than 10 and the value of 'i' will increase by 1 each time the loop continues.

Program
public class Main
{
	public static void main(String[] args) 
	{
		int i=1;
		do
		{
		  System.out.println(i);
		  ++i;
		}
		while(i<=10);
	}
}
Run

do-while Loop Example 2

In the example below, we have found out all the even numbers between 10-50. Here min = 10, max = 50 values are taken from the beginning. While I have conditioned the loop that if the min number is more than the max number then it will exit the loop otherwise the loop will continue Each time the loop runs, the value of the min number will be incremented by 1.

Program
public class Main
{
	public static void main(String[] args) 
	{
		int min=10;
		int max=50;
		do
		{
		    if(min%2==0)
		    {
		     System.out.println(min);
		    }
		    ++min;
		}
		while(min<=max);
	}
}
Run