Mega Code Archive

 
Categories / Java Tutorial / Statement Control
 

The do-while Statement

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 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