Java Do while loop: in the previous post of our softwaretestingo blog we have discussed the while loop and In This post, we are going to discuss do..while loop. the do-while loop is some similarities to while loop. But the difference between while and do-while loop is, in while loop condition is evaluated first if the condition returns true then only the loop’s body will be executed. Still, in the do-while loop, the body of the loop is executed first after that the condition evaluated.
Do while loop Syntax
the syntax for do-while loop looks like below:
do { // statements } while (expression);
Note: The expression for the do-while loop must return a boolean value that is true or false; otherwise, you will get a compile-time error.
If you have noticed that the boolean expression is at the end of the loop, so before evaluating, we have run the statements for once. After that, only we evaluating the expression if the expression returns true, the flow jumps to the statements, and again the loop body statements will be executed. This process will run until the expression returns false.
package java_Basics; public class DoWhileLoop_Example { public static void main(String[] args) { int i = 5; do { System.out.println(i); i++; } while (i <= 10); } }
Output:
5 6 7 8 9 10
Infinite do-while loop
If the expression always returns a true value, then the loop will run for indefinitely times. In that case, we have to quit the loop manually by pressing the ctrl+c.
package java_Basics; public class DoWhileInfiniteLoop_Example { public static void main(String[] args) { int x = 100; do { System.out.println("This is an infinite loop" ); x++; }while( x > 10 ); } }
Do While Vs While loop
If your requirement is to execute at least once the statements of the loop body area, even the conditional expression returns false then that time it is recommended to use a do-while loop. Otherwise its always better to use while loop. Because the Java while loop it looks cleaner than the do-while loop.
Ref: Article
Leave a Reply