A do-while
loop in Java is a control flow statement that allows you to execute a block of code repeatedly until a condition is met. The do-while
loop is similar to a while
loop, but the difference is that the do-while
loop always executes the loop body at least once, even if the condition is false
.
Here's the basic syntax of a do-while
loop in Java:
do { // Loop body } while (condition);
The loop body is executed first, and then the condition is evaluated. If the condition is true
, the loop body is executed again. This process is repeated until the condition becomes false
.
Here's an example of how you can use a do-while
loop in Java:
int i = 0; do { System.out.println(i); i++; } while (i < 5);
In this example, the loop body will print the value of i
and then increment it by 1
. The loop will continue to execute as long as i
is less than 5
. The output of this loop will be:
0 1 2 3 4
Note that the condition is evaluated at the end of each iteration, so the loop body is always executed at least once. This is different from a while
loop, which checks the condition before executing the loop body.
You can use a do-while
loop to perform a task repeatedly until a certain condition is met, or to execute a block of code at least once before entering a while
loop. You can also use a break
statement inside the loop body to exit the loop prematurely, or a continue
statement to skip the rest of the current iteration and move on to the next one.