Difference between While and Do While in Java

What are the difference between While and Do While in Java Programming Language with a practical example?

Difference between While and Do While in Java

Although Do While loop and While loop in Java looks similar, they differ in the order of execution.

  • In Java While loop, the condition is tested at the beginning of the loop, and if the condition is True, then only statements in that loop will be executed. So, the While loop executes the code block only if the condition is True.
  • In Java Do While loop, the condition is tested at the end of the loop. So, the Do While executes the statements in the code block at least once even if the condition Fails.

Maybe you are confused, and I think you will understand it better when you see the example. Let us write the same program using Java While loop and Do While loop to understand the order of execution.

Java While loop example

In this Java program, we are declaring integer variable Number and assigned value zero to it. Next, We will check whether Number (value = 0) is greater than ten or not to fail the condition deliberately. There is one more System.out.println statement outside the While loop and this statement will execute after the while loop.

package Loops;

public class WhileLoop {
	
	public static void main(String[] args) {
		int number = 0;
		
		while (number > 10)  {
			System.out.println("Number is Greater Than 10");
		}
		System.out.println("This Statement is Coming from Outside of while loop");
	}
}
Difference between While and Do While in Java 1

Java Do While Loop example

In this program, We are going to write the same example using Do while loop

package Loops;

public class DoWhileDiff {
	
	public static void main(String[] args) {
		int number = 0;
		
		do {
			System.out.println("Number is Greater Than 10");
		}while (number > 10);
		System.out.println("This Statement is Coming from Outside of do while loop");
	}
}
Number is Greater Than 10
This Statement is Coming from Outside of do while loop

Although the condition fails, the statement inside the loop executed once. Because the do while loop condition tested after the execution of the statements. We hope you understood the difference.

Comments are closed.