The do/while loop is a variant of the while loop.
Unlike the while loop, the do/while loop ensures that the code block is executed at least once before the condition is evaluated. If the condition remains true, the loop will continue to execute.
Syntax
do { // code block to be executed } while (condition);
The example below uses a do/while loop.
The loop executes the code block once, then checks the condition. If the condition is true, the loop repeats. This ensures the code block runs at least once, even if the condition is false initially.
Example
In this example, the code inside the loop will execute at least once, incrementing the variable counter
and printing its value until counter
is no longer less than 5.
int counter = 0; do { System.out.println(counter); counter++; } while (counter < 5);