Do While Loop in Java
The do while loop in Java is an iteration statement that is used to execute a block of code repeatedly until a specified condition becomes false.
Unlike the while loop, the do while loop executes the code block at least once before checking the condition.
What is Do While Loop in Java?
A do while loop in Java is a control flow statement that executes the loop body first and checks the condition afterward. If the condition is true, the loop continues; otherwise, it stops.
The do while loop is called an exit-controlled loop because the condition is checked after executing the statements inside the loop.
Syntax of Do While Loop in Java
do {
// code to execute
} while (condition);
Components of Do While Loop
do
Contains the block of code that executes before checking the condition.
condition
Determines whether the loop should continue or stop.
update
Changes the loop variable to control the number of iterations.
How Do While Loop Works in Java?
- The statements inside the do block execute first.
- After execution, the condition is checked.
- If the condition is true, the loop runs again.
- If the condition is false, the loop terminates.
Example of Do While Loop in Java
public class Main {
public static void main(String[] args) {
int i = 1;
do{
System.out.println(i);
i++;
} while(i <= 5);
}
}
2
3
4
5
Do While Loop Example with User Input
The do while loop is commonly used when we want to execute a task first and then ask the user whether to continue or not.
int number = 1;
do{
System.out.println("Number: " + number);
number++;
} while(number <= 3);
Difference Between While and Do While Loop
- While Loop: Checks the condition before executing the code.
- Do While Loop: Executes the code first and checks the condition later.
- While loop may execute zero times, but do while executes at least once.
Advantages of Do While Loop in Java
Executes Once
Executes the code block at least one time.
Simple Logic
Useful for programs where execution is required before checking.
Flexible
Suitable for menu-driven and interactive programs.
When to Use Do While Loop?
- When code must execute at least once.
- When taking user input repeatedly.
- When creating menu-based applications.
- When the stopping condition depends on execution results.