Java Do-While Loop (Guaranteed One-Time Execution)

✅ What is a Do-While Loop?

The do-while loop in Java is a variation of the while loop that guarantees at least one execution of the loop body, even if the condition is false at the start. This is because the condition is checked after executing the loop body.

It is helpful when you want the loop to run at least once, such as when getting user input, showing a menu, or performing a repetitive task before checking conditions.


🧠 Syntax of the Do-While Loop

do {
// Code to be executed
} while (condition);
  • do: Starts the loop block.

  • condition: The loop continues if this is true.

  • The condition is evaluated after the code runs.


🎯 Example 1: Print Numbers from 1 to 5

public class DoWhileExample {
public static void main(String[] args) {
int i = 1;

do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
}
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Even if i starts at 1, the condition (i <= 5) is checked after the loop runs, so the first print always happens.


🎯 Example 2: Run Loop Even When Condition is False

public class SingleRun {
public static void main(String[] args) {
int i = 10;

do {
System.out.println("This runs once even if condition is false!");
} while (i < 5);
}
}

Output:

This runs once even if condition is false!

In this case, even though i < 5 is false, the message is printed once because the condition is checked after the first run.


🔁 Do-While vs While: Key Differences

Feature While Loop Do-While Loop
Condition Check Before executing code After executing code
Minimum Execution 0 times (if false) At least 1 time
Use Case When unsure to start When one run is needed

✅ When to Use Do-While Loop

  • You want the loop body to execute at least once, no matter what.

  • Ideal for menu-driven programs, login attempts, or data entry loops.

  • Great for repeat-until logic, where action is required before condition check.

Related Posts