JavaDo/While Loop
The Do/While Loop
Thedo/while loop is a variant of thewhile loop. This loop will execute the code blockonce, before checking if the condition istrue. Then it willrepeat the loop as long as the condition istrue.
Syntax
do { // code block to be executed}while (condition);Note: The semicolon; after thewhile condition is required!
Do/While Example
The example below uses ado/while loop. The loop will always be executed at least once, even if the condition isfalse, because the code block is executed before the condition is tested:
Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end!
Condition is False from the Start
In thewhile loop chapter, we saw that if the condition isfalse at the beginning, the loop never runs at all.
Thedo/while loop is different: it will always run the code blockat least once, even if the condition isfalse from the start.
In the example below, the variablei starts at 10, soi < 5 is false immediately. Still, the loop runs once before checking the condition:
Summary: Ado/while loop always runs at least once, even if the condition is false at the start. This is the key difference from awhile loop, which would skip the code block completely in the same situation.
This behavior makesdo/while useful when you want something to happen at least once, such as showing a message or asking the user for input.

