do-while loop** in Java — it’s a very useful control structure, especially when you want the code to run at least once no matter what.


🔁 What is a do-while Loop?

A do-while loop is a type of looping control structure that:

  • Executes the loop body first
  • Then checks the condition
  • If the condition is true, it repeats the loop

🧠 Syntax:

do {
   // Code to be executed
} while (condition);

📌 Key Features:

  1. Runs at least once, even if the condition is false.
  2. Condition is checked after the loop body.

✅ Example:

public class DoWhileExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Value of i: " + i);
            i++;
        } while (i <= 5);
    }
}

🔍 Output:

Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5

🔥 What if the condition is false at first?

int i = 10;
do {
    System.out.println("Hello");
} while (i < 5);

Output:

Hello

✅ Even though the condition i < 5 is false, the message is printed once!


🆚 Difference: while vs do-while

Feature while loop do-while loop
Condition checked Before the loop body After the loop body
Loop runs Only if condition is true At least once
Syntax clarity Short and clean Slightly more code

🎯 Use Case:

Use do-while when you want to guarantee one execution — e.g., taking user input at least once and continuing if user wants.