Witscale Test Center

5.3 Iterative statements while, do-while and for > 5.3.2 The do-while loop


5.3.2 The do-while loop

The do-while loop is also good when you want to execute a block based on some condition. The general format of do-while loop is:

 

do{

     [Statements;]

} while(booleanExpresion);

 

 

The booleanExpresion is evaluated once at the end of the loop. If the condition is true then the further iteration of the statements takes place. This behavior is very similar to while loop with one difference. The condition is evaluated at the end of the do-while loop. Therefore the statement inside the do-while are guaranteed to executed at least once no matter what the condition evaluates to. Therefore, the following code will print the number 102:

 

int number = 102;

do {

  System.out.println(number);   // executed once

  number = number + 2;          // executed once 

 } while (number <= 100);

 

Note that the while() in do-while ends with a semicolon. If you forget to give it, your code fails to compile.

 

 

The conditions in while and do-while must evaluate to a value of boolean type. For exam, watch out for the invalid arguments (Similar to the if statement arguments in table 5.1) for the while and do-while. For instance, while(1) {} is an invalid while() statement as the condition is not of boolean type.