The do-while
loop in Java is a type of control flow statement used to execute a block of code repeatedly based on a condition. The key difference between the do-while
loop and other loops (like for
and while
) is that the condition is checked after the execution of the code block, ensuring that the code inside the loop is always executed at least once.
Syntax
- The loop executes the statement(s) inside the block first before checking the condition.
- It ensures that the code inside the loop is executed at least once, regardless of the condition.
- The condition is evaluated at the end of each iteration.
1 2 3 |
do { // code block } while (condition); |
- do: Starts the loop and the code block that needs to be repeated.
- condition: This is a boolean expression that is evaluated after each iteration. If the condition evaluates to
true
, the loop continues; if it evaluates tofalse
, the loop stops. - The code block inside the
do
part will always execute at least once, even if the condition is false initially.
Example
1 2 3 4 5 6 7 8 9 10 11 |
public class DoWhileExample { public static void main(String[] args) { int i = 1; // DO-WHILE loop do { System.out.println(i); // prints the value of i i++; // increment the value of i } while (i <= 5); // the loop will continue as long as i is less than or equal to 5 } } |
Output
1 2 3 4 5 |
1 2 3 4 5 |
- Initially, the value of
i
is 1. - The statement inside the
do
block prints the value ofi
, and theni
is incremented by 1. - After the block is executed, the condition
i <= 5
is checked. Sincei
is 6 after the fifth iteration, the loop stops.
A do-while
loop is particularly useful when you need to ensure that the code inside the loop is executed at least once, regardless of the condition. For example, when validating user input or when a specific action must be performed at least once before checking a condition.
In contrast, a while
loop checks the condition before the code block is executed, so if the condition is initially false
, the code may never run.