do-while
The do-while loop in Java is a control flow statement that allows you to execute a block of code at least once, and then repeatedly as long as a specified condition remains true. This loop is unique because it checks the condition after running the code block, guaranteeing at least one execution.
Syntax:
Syntax:
do { // Code to execute} while (condition);
How It Works
Example: Print Numbers 1 to 5
- The code inside the do block runs first.
- After the block executes, the condition is checked.
- If the condition is true, the loop repeats.
- If the condition is false, the loop stops.
Example: Print Numbers 1 to 5
public class DoWhileLoop { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while (i <= 5); }}
Output:
1
2
3
4
5
Key Points
- The do block always executes at least once, even if the condition is false from the start.
- The condition is checked after the code block runs.
- Useful when you want the loop to run at least one time, such as when displaying a menu or asking for user input.
When to Use do-while
- When you need guaranteed execution of the code at least once.
- When the condition to repeat depends on something that happens inside the loop.
Tips: Use the do-while loop for scenarios like input validation, menu-driven programs, or repeating actions that must happen at least once.