Java Repetition Statements: do while Loops
do while Loops
We have seen with the for loop and while loop that a code block is executed if an expression is true, the do while loop is similar but with one key difference: the code block is executed once before the expression is evaluated. This means that no matter what, the code block will ALWAYS be executed. The general syntax is:
do {
statements;
} while (expression);
Typically with loops, the do while starts with an appropriate keyword but did you notice that the code block starts immediately after that keyword? This is why the code block of a do while loop will always execute at least once no matter what the expression resolves to. After the code block we have the while keyword followed by the expression to be tested. Let’s see this in practice:
int count = 1; do { System.out.println("Count: " + count); count++; } while (count < 5);
Here we hav a variable called count initialised with a value of 1. The do while loop has an expression that checks if count is less than 5 (count < 5) which will be checked but not before the code block is executed. The code block contains an output of the current value of count followed by an statement that increments count (count++;). The output will be:
run: Count: 1 Count: 2 Count: 3 Count: 4 BUILD SUCCESSFUL (total time: 0 seconds)
Did you get the same output?
What would you expect the output to be if the expression always resolves to false?
Try this again but change the expression to check for a value of count to something that will resolve to false.
Well done if you guessed that the output would be equivalent to one execution of the code block with the initial value of count!
The change we made was to reduce the value that expression checks count against to something less than the initial value of count. This would mean that the expression could only ever resolve to false:
int count = 1; do { System.out.println("Count: " + count); count++; } while (count < 1);
Type this code into your IDE, the output should be:
run: Count: 1 BUILD SUCCESSFUL (total time: 0 seconds)
The do while loop is the perfect choice when you need your code to always execute the code block once no matter what. As with all loop, care should be taken to prevent perpetual loops.