The do-while loop is an exit-controlled loop. Unlike the for and while loops that evaluate their conditions at the entry gate, the do-while loop executes its statement body first, and only evaluates the continuation condition at the end of each iteration.
// Do-While Syntax (Notice mandatory trailing semicolon!)
do {
// Statements executed at least once
// Update expression
} while (boolean_condition);
A ubiquitous assignment in BCA and CS lab exams is building a menu-driven program that runs until the user explicitly enters an exit command:
import java.util.Scanner;
public class MenuDrivenApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("
=== VEEWOM BANKING MENU ===");
System.out.println("1. Check Account Balance");
System.out.println("2. Deposit Funds");
System.out.println("3. Withdraw Funds");
System.out.println("4. Exit Application");
System.out.print("Enter your selection (1-4): ");
choice = scanner.nextInt();
switch (choice) {
case 1 -> System.out.println("Your Current Balance: $5,420.00");
case 2 -> System.out.println("Deposit window opened.");
case 3 -> System.out.println("Withdrawal processing...");
case 4 -> System.out.println("Thank you for using Veewom Banking. Goodbye!");
default -> System.out.println("Invalid selection! Please enter a number 1 to 4.");
}
} while (choice != 4); // Loop repeats until user picks 4
scanner.close();
}
}
| Feature | While Loop | Do-While Loop |
|---|---|---|
| Control Type | Entry-Controlled (Pre-test) | Exit-Controlled (Post-test) |
| Condition Check | Tested before loop body executes | Tested after loop body executes |
| Minimum Executions | 0 times (if initial condition is false) | 1 time guaranteed |
| Trailing Semicolon | No semicolon after while(cond) |
Mandatory semicolon after while(cond); |
Exam Tracing Question: "What is the output of the following Java code?"
int count = 10;
do {
System.out.print(count + " ");
count++;
} while (count < 5);
Output: 10
Explanation: Even though the condition count < 5 (11 < 5) is completely false from the start, the loop body executes once first, printing 10 and incrementing count to 11. The condition then fails and halts further loops.
Now let us explore the For Loop, nested loops, and pattern printing. Proceed to: Java For Loop →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Entry-controlled comparison.
Standard counting loop.
Early exit controls.
Pairing switch with menu loops.