Learn Java Basics
About Lesson

The do-while loop in Java is a type of loop that is similar to the while loop, but with one important difference: the loop body is executed at least once, regardless of whether the loop condition is initially true or false. Here’s how the do-while loop works:

  1. Loop body execution: The code in the loop body is executed once, before the loop condition is checked.

  2. Condition evaluation: The loop condition is then evaluated. If the condition is true, the loop body is executed again. If the condition is false, the loop terminates and control passes to the next statement following the loop.

  3. Loop iteration: If the loop condition is true, the loop body is executed again, and the process repeats from step 2.

Here’s an example of a do-while loop that reads input from the user and repeats until the user enters a positive number:

int number;
do
{
System.out.print("Enter a positive number: ");
number = in.nextInt();
}
while (number <= 0);

In this example, the loop body prompts the user to enter a positive number and reads the input from the user. The loop continues to execute as long as the user enters a non-positive number, because the condition (number <= 0) is true. Once the user enters a positive number, the loop terminates and control passes to the next statement following the loop.

The do-while loop is useful when you need to execute a block of code at least once, regardless of the condition, and then repeat the block of code until a condition is met.

Difference between while and do-while loop

Here is a table comparing the differences between while and do-while loops in Java:

Feature while loop do-while loop
Syntax while (condition) { // loop body } do { // loop body } while (condition);
Condition Evaluation Condition is evaluated first, and if false, the loop body is skipped Loop body is executed at least once, and then the condition is evaluated
Loop Body Execution Loop body is executed only if the condition is true Loop body is executed at least once, regardless of the condition
Use Case Use when the loop body should be executed zero or more times, based on the condition Use when the loop body should be executed at least once, regardless of the condition
Initialization Initialization of variables is done outside the loop Initialization of variables can be done inside or outside the loop

Join the conversation