The do-while
construct in Java is a looping structure designed to repeatedly execute a set of statements as long as a specified condition remains true. Unlike the while
loop, the do-while
loop guarantees the execution of its body at least once, even if the condition is false from the start.
The do-while
construct in Java comes in two forms:
First Form (using only while
keyword):
while (condition is true) {
// Statements
}
Second Form (using both do
and while
keywords):
do {
// Statements
} while (condition is true);
while
construct initiates the execution of its body only if the condition is true. The statements may not be executed if the condition is false from the start.do-while
construct always executes the statements in its body at least once, even if the condition is false initially.Example 1: Using a while
loop to print 10 numbers from 1 to 10:
int i = 1;
while (i <= 10) {
System.out.println(i);
i++;
}
Example 2: Utilizing a do-while
loop to read input from the command line until an empty string is entered:
String input = null;
do {
System.out.print("Enter input: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
input = reader.readLine();
System.out.println("Your input: " + input);
} while (!input.equals(""));
By comprehending the nuances of the do-while
construct, you gain a powerful tool for creating robust and flexible loops in your Java programs.