The do-while Statement : Do While Loop « Statement Control « Java Tutorial






The do-while statement is like the while statement, except that the associated block always gets executed at least once.

Its syntax is as follows:

do {
    statement (s)
} while (booleanExpression);

Just like the while statement, you can omit the braces if there is only one statement within them. However, always use braces for the sake of clarity.

public class MainClass {

  public static void main(String[] args) {
    int i = 0;
    do {
      System.out.println(i);
      i++;
    } while (i < 3);
  }

}

This prints the following to the console:

0
1
2

The following do-while demonstrates that at least the code in the do block will be executed once even though the initial value of j used to test the expression j < 3 evaluates to false.

public class MainClass {

  public static void main(String[] args) {
    int j = 4;
    do {
        System.out.println(j);
        j++;
    } while (j < 3);
  }

}

This prints the following on the console.

4








4.5.Do While Loop
4.5.1.The do-while Statement
4.5.2.The do while loop in action