Launch your tech mastery with us—your coding journey starts now!
Course Content
Array Handling
0/1
String Handling
0/1
Wrapper Classes
0/1
Collections in Java
0/1
Packages
0/1
File Handling
0/1
Multithreading
0/1
Java Networking
0/1
Core Java

 

🔁 do-while loop in Java

When you want your code to run at least once, no matter what, the do-while loop is your best option. Unlike while and for, which check conditions before executing, the do-while loop checks the condition after running the code block.

This makes it perfect for menus, input validation, and interactive programs. 🚀


🧐 What is a do-while loop?

A do-while loop executes a block of code once before checking the condition. Then, it continues running as long as the condition is true.

👉 Syntax:

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

🔍 How it Works

1️⃣ Code block executes once (even if condition is false).
2️⃣ Condition is checked.
3️⃣ If true → loop repeats.
4️⃣ If false → loop stops.

✅ Example 1: Print Numbers from 1 to 5

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

Output:

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

🚀 Why use do-while loop?

✔️ Ensures code runs at least once.
✔️ Great for menu-driven programs.
✔️ Useful for user input validation.


⚡ Popular Examples of do-while loop

1️⃣ User Input Menu

Scanner sc = new Scanner(System.in);
int choice;
do {
    System.out.println("1. Play");
    System.out.println("2. Settings");
    System.out.println("3. Exit");
    System.out.print("Enter your choice: ");
    choice = sc.nextInt();
} while(choice != 3);

2️⃣ Guess the Number Game

int secret = 7;
int guess;
Scanner sc = new Scanner(System.in);
do {
    System.out.print("Guess the number (1-10): ");
    guess = sc.nextInt();
} while(guess != secret);

System.out.println("🎉 Correct! You guessed it!");

3️⃣ Execute Once Even if Condition is False

int num = 10;
do {
    System.out.println("This runs once!");
    num++;
} while(num < 0);

Output:

This runs once!

💡 Pro Tips

✅ Perfect for menus, input-driven apps, and games.
✅ Always ends with a semicolon (;) → don’t forget it!
✅ Be careful with conditions → or you’ll end up in an infinite loop.

🔑 Difference between while and do-while

Feature while loop do-while loop
Condition check Before code runs After code runs
Minimum execution 0 times (if false initially) 1 time (always executes once)
Use case Unknown iterations Menus, input validation

 

In short:
The do-while loop is the go-to loop when you need the code to run at least once, making it highly useful in interactive and menu-based Java programs.