While Loop in Java
The do-while
loop in Java is similar to the while loop. The main difference is that the loop body gets executed first and then the terminating condition gets evaluated after. This means that the loop is guaranteed to run at least once. It is entirely possible to just use the while
loop, however the do-while
loop can offer a more elegant solution at times.
Do-While Loop Concepts
The parts of a do-while
loop are typically handled in the following order: initialization, loop body, update, and terminating condition. We first want to have a variable created to be used to evaluate with the terminating condition. The loop body gets executed because it is guaranteed to run the first time. Then we perform some sort of update on the variable that will affect the evaluation of the terminating condition. Then the terminating condition decides whether the loop body should execute again or not.
Do-While Loop Example
An example of using the do-while
loop is when we want to display instructions to the user until they have entered all the information needed, or they decide to quit the program. The loop body could be prompting the user for an action. Since the program is going to start with the prompt, we know the loop has to execute at least once.
Consider this program using the while
loop where we keep asking for input from the user until they decide to quit:
Scanner scanner = new Scanner(System.in);System.out.println("Enter 'q' to quit or any other button to continue:");String input = scanner.nextLine();while (input != "q") {System.out.println("Enter 'q' to quit or any other button to continue:");input = scanner.nextLine();}
In this scenario, we likely want to display the prompt to the user and accept input at least once. Using the do-while
loop we could write:
Scanner scanner = new Scanner(System.in);String input = "";do {System.out.println("Enter 'q' to quit or any other button to continue:");input = scanner.nextLine();} while (input != "q");
With the do-while
loop, showing the prompt and asking the user to enter in input gets executed immediately before evaluating whether the loop should run again.
Difference Between the while and do-while Loop
Here's an example to show that a do-while loop is guaranteed to run at least once, and a while loop is not:
int number = 5;while (number < 3) {System.out.println(number);number++;}
In this case, nothing will get printed out because the terminating condition is evaluated to false, so the loop body does not execute.
int number = 5;do {System.out.println(number);number++;} while (number < 3);
Now using the do-while loop, the value of 5
will get printed out because the loop body executes before evaluating the terminating condition.
Conclusion
Here we learned the do-while
loop and how it differs from the while
loop. Essentially the do-while
is a post-condition evaluation and the while
loop is a pre-condition evaluation.