Program Flow  «Prev  Next»
Lesson 8A twist on the while loop
Objective Find out how to use do loops.

do-while loop in Java

The do-while loop is very similar to the while loop.
The do-while statement is similar to a while loop except that the body of the loop always executes at least once. It consists of the
  1. do keyword
  2. followed by a statement,
  3. the while keyword, and
  4. then a logical expression enclosed in parentheses.

The following block describes the syntax for the do-while loop:

do
  Statement
while (LoopCondition);

An alternative syntax is
do 
  <statement> 
while (<boolean-expression>);


Typically, the body of the do-while loop, as represented by the statement, is a block statement. The following code snippet illustrates the use of the do statement. It is an improvement over the equivalent while loop used in the previous section, as it avoids prompting for a number before the loop starts:

int sum = 0;
int number;
Scanner scanner = new Scanner(System.in);
do {
 System.out.print("Enter a number: ");
 number = scanner.nextInt();
 if(number > 0 ) {
  sum += number;
 }
} while (number > 0);
System.out.println("The sum is " + sum);

When executed you should get output similar to the following:
Enter a number: 8
Enter a number: 12
Enter a number: 4
Enter a number: -5
The sum is 24

Why would a programmer use a do-while loop instead of a for loop in Java?

A programmer might choose to use a do-while loop instead of a for loop in Java in specific situations when the loop body needs to be executed at least once, regardless of the loop condition. The main difference between the two loop constructs is in their control structures and when the loop condition is checked:
  1. do-while loop: The loop condition is checked after the loop body has been executed. This means that the loop body will always execute at least once, even if the condition is false from the beginning.
    int count = 0;
    do {
        System.out.println("This message will be printed at least once.");
        count++;
    } while (count < 1);
    
  2. for loop: The loop condition is checked before the loop body is executed. If the condition is false at the beginning, the loop body will never execute.
    for (int count = 0; count < 1; count++) {
        System.out.println("This message may not be printed if the condition is false.");
    }
    
Here are some situations where a programmer might prefer to use a do-while loop instead of a for loop:
  1. When the loop body needs to execute at least once, and the condition is not guaranteed to be true at the beginning.
  2. When the loop condition depends on the result of a computation or user input processed within the loop body, and this computation or input must occur at least once.
  3. When the code readability is improved by separating the loop condition and loop body, such as when the loop condition is complex or depends on multiple variables.
In summary, a programmer uses a do-while loop instead of a for loop in Java when it is necessary to execute the loop body at least once, regardless of the loop condition, or when it improves code readability by separating the loop condition and loop body. However, both loops are powerful constructs, and the choice of which loop to use depends on the specific requirements of the problem being solved.


Note: The do-while statement differs from that of the while statement as the evaluation of the expression occurs at the end of the loop. This means that this statement will be executed at least once.
The do-while loop is simply a while loop with the LoopCondition moved to the end. Although this may seem like a minor change, there are situations where it is important for the Statement to execute before evaluating the LoopCondition, instead of afterward. The do-while loop is perfect in this type of situation. The do-while loop also guarantees that the Statement is executed at least once, regardless of the LoopCondition.

Following is an example of using the do-while loop:
boolean correct;
do {
 answer = askQuestion();
 correct = isCorrect(answer);
}
while (!correct);


The code could be used to ask a question repeatedly until you get the correct answer. If you interpret this code in English, it is basically saying "ask the question and if the answer is not correct, ask it again."
This is a perfect usage of the do loop since the answer is nott checked until after the question is asked. Although you could use a while loop to accomplish the same thing, it would be more difficult to understand.

Quiz Question:

Which of these statements are valid when occurring by themselves?
  1. while() break;
  2. do { break ; } while (true) ;
  3. if (true) { break ; } (When not inside a switch block)
  4. switch (1) { default : break; }
  5. for ( ; true ; ) break ;

Select 3 options:

Answer: b, d, e Explanation:
a. The condition expression in a while header is required.
c. Cannot have 1) break or 2) continue in an 'if' or 'else' block.
d. You can use a constant in a switch(...) statement;
It is not possible to break out of an if statement. But if the if statement is placed within 1) a labeled block, 2) a switch statement, or 3) a loop construct, the usage of break in option c would be valid.