The syntax for the do/while loop in Java guarantees the code block is executed at least once before the condition is tested. This is different from a while loop, which may never execute if its condition is initially false.
The basic syntax
The structure of a do/while loop is as follows:
do {
// Code block to be executed
} while (condition);
Use code with caution.
- The
dokeyword marks the beginning of the loop, followed by the code block enclosed in curly braces ({...}). - The
whilekeyword comes after the code block, followed by a booleanconditionin parentheses(...). - A semicolon (
;) is required at the end of thewhilestatement to complete the syntax.
How the do/while loop works
The execution flow of a do/while loop is an "exit-controlled" process that follows these steps:
- Execute the
doblock: The program runs the code inside the curly braces of thedoblock at least once. - Evaluate the
whilecondition: After the first execution, the booleanconditionis checked. - Repeat or terminate:
- If the
conditionistrue, the program jumps back to thedoblock and executes it again. - If the
conditionisfalse, the loop terminates, and the program continues with the next statement after the loop.
- If the
Example of a do/while loop
This example demonstrates how the loop runs at least once, even when the condition is false.
public class DoWhileDemo {
public static void main(String[] args) {
int x = 10;
do {
// This block is guaranteed to execute once.
System.out.println("The value of x is: " + x);
x++;
} while (x < 10); // The condition is initially false.
System.out.println("Loop terminated. Final value of x is: " + x);
}
}
Use code with caution.
Output:
The value of x is: 10
Loop terminated. Final value of x is: 11
Explanation:
- The
doblock runs first, printing"The value of x is: 10"and incrementingxto11. - The
whilecondition (x < 10) is then evaluated. Since11is not less than10, the condition isfalse. - The loop terminates. If a regular
whileloop had been used instead, the output would have been nothing, as the condition would have been checked first.
When to use a do/while loop
The primary use case for a do/while loop is when you need to perform an action at least one time, regardless of whether a condition is met. Common scenarios include:
- Input validation: Prompting a user for input and repeating the prompt until valid data is entered.
- Menu-driven programs: Displaying a menu of options to a user at least once, then repeating based on their selection.
- Games: Asking if a player wants to play again after a round has concluded.
Advanced do/while loop concepts
Nested do/while loops
You can place one do/while loop inside another. The inner loop will execute completely for every single iteration of the outer loop, allowing you to handle more complex, multi-layered tasks.
public class NestedDoWhile {
public static void main(String[] args) {
int i = 1;
do {
int j = 1;
do {
System.out.print(i + "*" + j + " ");
j++;
} while (j <= 3);
i++;
System.out.println(); // New line after inner loop completes
} while (i <= 3);
}
}
Use code with caution.
Output:
1*1 1*2 1*3
2*1 2*2 2*3
3*1 3*2 3*3
Controlling loop execution
The break and continue statements can be used inside a do/while loop to modify its control flow.
breakstatement: This immediately terminates the entire loop, regardless of whether the condition is met.continuestatement: This skips the rest of the current iteration and jumps to the next one.
public class LoopControl {
public static void main(String[] args) {
int i = 0;
do {
i++;
if (i == 3) {
System.out.println("Skipping iteration 3 with continue.");
continue; // Skips printing for this iteration
}
if (i == 5) {
System.out.println("Breaking out of the loop at 5.");
break; // Exits the loop entirely
}
System.out.println("Current value of i: " + i);
} while (i < 10);
}
}
Use code with caution.
Output:
Current value of i: 1
Current value of i: 2
Skipping iteration 3 with continue.
Current value of i: 4
Breaking out of the loop at 5.