How Do You Create a Do-While Loop in Java?

How Do You Create a Do-While Loop in Java?

To create a do-while loop in Java, first supply an opening "do" statement, then follow it with the block of code to loop through. Finally, append a "while" statement to evaluate at the end of each cycle. The do-while loop resembles this pattern: do{ //code to loop } while(Boolean expression);.

  1. Write the opening "do" statement

    On a new line in the code editor, type "do {".

  2. Supply the code to loop through

    Adhering to the conventions of the Java coding style guide you are following, enter the code that will be looped through after the opening curly bracket. After the terminating semicolon on the last line of looped code, close the "do" statement with a closing curly bracket. Do not follow the closure with a semicolon.

  3. Add the "while" statement

    After the closure, add the "while" statement by typing "while();". Be sure to terminate the "while" statement with a semicolon.

  4. Insert the Boolean expression

    Insert the Boolean expression between the parenthesis of the "while" statement. Unlike a straight "while" loop, the Boolean expression is evaluated after each cycle, rather than before. So long as the Boolean expression evaluates to "true," code execution returns to start of the "do" statement with each cycle. The cycle breaks when the Boolean expression evaluates to "false" or when "break;" is encountered in the looped block.