Java Do-While Loop

Naveen AnamaneniUpdated · 4 min read

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

while checks first; do-while runs first
Compare.java▶ Try it
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);
    }
}
Output
do-while body: 10

Both 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".

AtmMenu.java▶ Try it
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);
    }
}
Output
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 you

How it works

  1. The menu prints before any check, so the user always sees it at least once.
  2. choice is declared before the loop (line 7), because the condition on line 21 is outside the braces and still needs it.
  3. 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

AskAge.java▶ Try it
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);
    }
}
Output
Enter age (1-120):
Enter age (1-120):
Enter age (1-120):
Age accepted: 25

The 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

  1. Easy: Ask for a PIN until the user types 4321, then print "Welcome".
  2. 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.

Quick check: do-while

4 questions
1How many times does a do-while body run if the condition is false from the start?
2What does do-while need at the end that while doesn't?
3Which is a good fit for do-while?
4Where should the variable used in the condition be declared?

Key Takeaways

Was this tutorial helpful?

Lesson 60 of 482