Java Do-While Loop
An ATM always shows its menu at least once: you can't decide whether to quit until you've seen the options. A do-while loop works the same way. It runs the body first, and checks the condition afterwards, so the body always runs at least once.
while vs do-while
public class Compare {
public static void main(String[] args) {
int a = 10;
while (a < 5) {
System.out.println("while body: " + a);
}
int b = 10;
do {
System.out.println("do-while body: " + b);
} while (b < 5);
}
}do-while body: 10Both conditions are false from the start. The while body never runs; the do-while body runs once, then the check fails and the loop ends.
A Menu That Repeats
Menus are the classic use: show the options, act on the choice, and repeat until the user picks "exit".
import java.util.Scanner;
public class AtmMenu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int balance = 5000;
int choice;
do {
System.out.println("1. Balance 2. Withdraw 500 3. Exit");
choice = sc.nextInt();
if (choice == 1) {
System.out.println("Balance: Rs. " + balance);
} else if (choice == 2) {
balance -= 500;
System.out.println("Please take your cash");
} else if (choice == 3) {
System.out.println("Thank you");
} else {
System.out.println("Invalid choice");
}
} while (choice != 3);
}
}1. Balance 2. Withdraw 500 3. Exit
Balance: Rs. 5000
1. Balance 2. Withdraw 500 3. Exit
Please take your cash
1. Balance 2. Withdraw 500 3. Exit
Thank youHow it works
- The menu prints before any check, so the user always sees it at least once.
choiceis declared before the loop (line 7), because the condition on line 21 is outside the braces and still needs it.- The loop repeats until the user chooses 3.
Try it yourself: run it and type 2, 2, 1, 3. What balance is shown?
Checking Input Until It's Valid
import java.util.Scanner;
public class AskAge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age;
do {
System.out.println("Enter age (1-120):");
age = sc.nextInt();
} while (age < 1 || age > 120);
System.out.println("Age accepted: " + age);
}
}Enter age (1-120):
Enter age (1-120):
Enter age (1-120):
Age accepted: 25The question is asked at least once, and asked again as long as the answer is out of range: -4 and 200 are rejected, 25 is accepted.
Common Mistakes
Forgetting the final semicolon. } while (choice != 3) without ; is a compile error.
Declaring the condition variable inside the braces. The condition is outside the block, so a variable declared inside isn't visible there. Declare it before do.
Using do-while when zero rounds is possible. If the body shouldn't run when the condition is false at the start, use while.
Practice
- Easy: Ask for a PIN until the user types 4321, then print "Welcome".
- Harder: Write a guessing game: the secret number is 37; keep asking for guesses and say "Higher" or "Lower" until the guess is correct, then print how many guesses it took.
Key Takeaways
Was this tutorial helpful?