The Do-While Loop in Java

Do-While Loop in JavaA common structure in programming is the loop. A loop is used any time that the same task must be repeated. The existence of loops in programming makes it easy to accomplish repetitive tasks very quickly and with a minimum of code. The nature of the task will determine the exact type of loop that must be run. In this article we will look at the do-while loop in Java and describe how it is used and when it is the correct loop to use for a programming task. You can get a more comprehensive introduction to Java with the course Programming Java for Beginners – The Ultimate Java Tutorial.

The structure of a Java Do-While Statement is as Follows:

do{
loop statement;
.
.
.
loop statement;
} while (conditional test);

The do keyword is followed by the loop body statement contained in curly braces. After the loop body, the keyword while is followed by a conditional test in parentheses. This entire block constitutes the do-while loop.

When to Use a Do-While Loop

If the exact number of times to run a loop is known, it is usually more appropriate to use the for loop. Technically, either loop can be written to perform a task a known amount of times. The for loop makes it more explicit that this is happening and provides for better readability and understanding for anyone reading the source code.

A do-while loop is used when the number of times the loop should iterate is not predictable. For the do-while loop, you set a condition which must hold true for the loop to continue running. The do-while loop will execute at least once, because the condition is not checked until the bottom of the loop. It is an exit condition loop. If you have a case where the loop should not run unless a condition is true, you should use the while loop. The do-while loop is used when the loop must run at least once, and then continue or not depending on the conditional test statement.

Examples of Using the Do-While Loop

A classic situation for a do-while loop is for a menu or dialog that displays and waits for a response from the user. Perhaps the program encounters a situation where it is saving a file and finds an existing file with the same name. In this case, it must present a dialog to the user, no matter what, to ask whether the file should be overwritten. The program will then take action based on the user response. If the response is not defined, the dialog will be displayed again. If the response is defined, the program exits the loop and goes on to execute code based on the user response.

In rough form it would look like this:
do{
statement to initialize test variable to true;
statement(s) to display the dialog;
statement(s) to read the user response;
statments(s) to evaluate the user response;
** statement(s) to change test variable to false if user gave a valid response;
} while (test variable is true);
go on to execute code based on the response

Notice the statement with the ** label. A hazard in writing any loop is faulty logic that results in a loop that never ends. This may crash the device running the program, or at least make the program hang until the user can escape from it. Endless loops must be avoided for a user-friendly experience. This statement specifically ensures that the test condition will become false and the loop will exit. Examine the code in your loop carefully to ensure that the condition will become false.

Again, in principle a while loop could be used, and the program logic would need to be adjusted. The test variable would need to be initialized before entering the loop and the logic would have to ensure that the dialog box is displayed once. The do-while loop is preferable because its logic fits the situation better and is a more readable and understandable solution. You can learn more about best practices in the article Java Best Practices for Layout, Comments and Naming Conventions.

Another good example for use of a do-while loop is an app that plays a game. The program has to let them play the game at least once – that’s the point of the program! When the game is over, the program asks the user if they want to play again. Based on the response, they play the game again or perhaps are presented with a menu of other choices if they chose not to play again. Seen in this way, apps that get input from the user are a series of do-while loops. Java is used in programming Android apps. You can learn more about Java and Android with the course Learn Android Programming in Java. For learning games try the course Building Your First Game For Android And The PC Using Java.

Do-while loops in Java are can be nested in the same way as other loops. In the game example, the play game-ask to repeat loop would likely contain many do-while loops that play the actual game. When nesting loops it is important to take care in how the test variable is used in each loop. The variables should be different for each loop. Watch for instances where one loop alters the test variable of the other and be very clear on how that will affect the conditional test statement.

The break and continue keywords can also be used with do-while loops. The break keyword is used if a situation is encountered where the loop should stop immediately. For example, suppose the user wins the game. Once this condition is met, then the game is over and the loop that is playing the game should stop executing. If the loops are nested, a break keyword in the inner loop will return to the parent loop. In our game example, the outer loop is the play game-ask to play again loop. The player would then be asked to play again. The continue keyword stops the loop at that point then returns to repeat the same loop again from the beginning.

This introduction should help with do-while loops. For more advanced Java programming, try the course Advanced Java Programming (Java SE 7).