In Java, a do-while
loop is a control structure that executes a block of code at least once, and then repeats the block as long as a given condition is true.
Here's the general syntax for a do-while
loop in Java:
do { // Code to be executed } while (condition);
The do-while
loop first executes the code in the block, and then evaluates the condition
. If the condition is true
, the loop will execute the code again. If the condition is false
, the loop will terminate.
Here's an example of how to use a do-while
loop to count from 1 to 5:
int i = 1; do { System.out.println(i); i++; } while (i <= 5);
This will output the following:
1 2 3 4 5
It's important to note that the do-while
loop will always execute the code in the block at least once, even if the condition is false
initially. This is in contrast to a while
loop, which will only execute the code in the block if the condition is true
initially.
You can use a do-while
loop to repeat a block of code an unknown number of times, or to execute the code at least once before checking the condition.