Do While Statement Tutorial

The do-while statement is a looping statement that executes a block of code, then evaluates an expression to see if it should loop again or not. Code inside of the do-while code block will execute at least once, even if the expression portion evaluates to false. Once the code from the code block has executed, the expression portion will be evaluated. Stopping the loop simply means that the expression portion will evaluate to false. Something unique to the do-while loop is that the (expression) portion MUST have a semicolon after the closing parenthesis. Here is the do-while loop structure:
do {
    Statements are executed;
} while (expression);
// don't forget the closing semicolon!



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md DoWhile
C:\Java>cd DoWhile
C:\Java\DoWhile>Notepad DoWhile.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class DoWhile {
    public static void main(String args[]) {
        boolean b = false;
        do {
            System.out.println("Statements are executed at least once - even if expression results in false.");
        } while (b);

        int i = 0;
        do {
            System.out.println(i);
            i++;
        } while (i < 10);
    }
}

Now switch back to the command prompt (CMD) and type in javac DoWhile.java and press Enter.
Now type in java DoWhile and press Enter.


C:\Java\DoWhile>javac DoWhile.java
C:\Java\DoWhile>java DoWhile
Statements are executed at least once - even if expression results in false.
0
1
2
3
4
5
6
7
8
9


Final thoughts

I rarely find an occasion to use the do-while loop that can't be better served using one of the other looping control flow statements. Just to reiterate - don't forget the semicolon at the end!


Tutorials