Introduction
When you're learning Java, loops are one of the most important concepts to understand. They allow a program to execute the same block of code repeatedly based on a condition.
Java provides several types of loops, including for, while, and do-while. Among them, the do-while loop is unique because it executes the loop body at least once before checking the condition.
This makes it particularly useful when an action needs to happen before deciding whether the program should continue.
*Example
*
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
A particularly good example for DEV.to would be a menu-driven program, because that's one of the situations where the "execute first, check later" behavior makes intuitive sense. The do-while loop is exit-controlled because its condition is evaluated after the body executes.
Real-world example idea
import java.util.Scanner;
public class MenuExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n--- Menu ---");
System.out.println("1. View Profile");
System.out.println("2. Settings");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Opening Profile...");
break;
case 2:
System.out.println("Opening Settings...");
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 3);
sc.close();
}
}
This example demonstrates why do-while can be useful: the menu needs to be displayed at least once, and afterward the program decides whether to display it again.
Conclusion
The Java do-while loop is useful when a block of code must execute at least once before a condition is checked. Unlike the while loop, which checks its condition before execution, the do-while loop checks the condition after executing the loop body.
Understanding this difference will help you choose the right loop for different programming situations, especially menu-driven programs, input validation, and repeated user interactions.
If you're building your Java fundamentals step by step, understanding loops such as for, while, and do-while is an important part of becoming comfortable with Java programming.
Top comments (0)