Sunday, 13 October 2019

Java Tutorials | do-while loop in Java

do while loop is similar to while loop with the only difference that it checks for condition after executing the statements, see syntax below.

do {
} while (condition);

Flow Chart: do-while loop

The Java do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time. After the execution of the statements once, the condition is checked for a true or false value. If it is evaluated to true, the next iteration of the loop starts. When the condition becomes false, the loop terminates which marks the end of its life cycle.

The Java do-while loop is executed at least once because the condition is checked after the loop body. So if you want to execute the loop at least once, it is recommended to use the do-while loop.

Java program do-while loop example
public class DoWhileTest {
     public static void main(String args[]) {
          int x = 11;
          do {
               //The line will be printed even if the condition is false
               System.out.println("Value of x: " + x);
          } while (x < 10);

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...