Do While Loop in Java

Do-while loop also let us achieve the make iteration. But there is a minor difference between while and do-while loop. But, before discussing that, let us see how do-while loop looks like.

Example:

public class WhileDemo {

	// we want to print 10 to 1 backwards
	//now using do-while loop
	public static void main(String[] args) {
		int i = 10; // initiate the count
		
		do{
			System.out.print(i + " "); 
			i--; // decrease the value of i by 1
		}
		while(i>0);
	}

}
Try It

The output will be:

10 9 8 7 6 5 4 3 2 1

Difference between while and do-while loop?

When we use while loop, it first checks if the condition is satisfied, then only, it goes inside the block. But, in do-while loop, for the first iteration, this loop doesn’t check for any condition. It straight goes inside the loop. Then, after executing the loop, it goes to while. It checks, if the condition holds. If holds, it goes inside the block again. If not, then passes the control to the immediate next statement of the loop.

Do-while is similar to a while loop, except that a do-while loop guarantees to execute the statement at least one time.

Let us see an example:

We can see the screenshot that, we started with i = 0 in both while and do-while loop. But, for while loop it did not enters the loop once as it checks on the start of every iteration. But for do –while, it prints 0, as it did not check for the first iteration.


Next > < Prev
Scroll to Top