Friday 31 March 2017

Difference between while and do-while loop

While loop and do while loop in java differ based on following parameter:

Execution process:

While loop checks the condition at the beginning of the loop.
If the condition is found to be true then only the statement inside the loop body gets executed.

int i= 7;
while(i<5){
//Inside while loop
System.out.print("condition is true");
i++;
}

From the above example, we see that first the condition, i<5, will be tested. And if the condition is true(in this case its false since i=7) then only the body inside loop will execute.
Since condition turns out to be false so the body inside while loop is not executed.


do while checks the condition at the end of the loop.
As the condition is tested at end of the loop so the body inside loop gets executed at least once, even in case the condition is found to be false.

int i= 7;
do{
//Inside do while loop
System.out.print("condition is true");
i++;
}while(i<5);

From the above example, we see that at first time entry inside loop there is no testing condition so the body inside do while loop gets executed. And then the condition, i<5, is getting checked at the end after body execution.
Even though the condition is false but the body gets executed once before the loop terminates.

Conclusion:

If you need a code where you want to execute your code at least once even if condition is false use do-while.
And if you are strict with condition check and don't want any execution for false outcome go for while loop.


You may also like to read:

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.