The do...while
loop differs from other loops in that it is guaranteed to execute at least once. It is also called the "post-test loop" structure because the conditional statement is performed after the main loop body.
int i = 0;
do {
i++;
System.out.println(i);
} while (i < 100); // Condition gets checked AFTER the content of the loop executes.
In this example, the loop will run until the number 100
is printed (even though the condition is i < 100
and not i <= 100
), because the loop condition is evaluated after the loop executes.
With the guarantee of at least one execution, it is possible to declare variables outside of the loop and initialize them inside.
String theWord;
Scanner scan = new Scanner(System.in);
do {
theWord = scan.nextLine();
} while (!theWord.equals("Bird"));
System.out.println(theWord);
In this context, theWord
is defined outside of the loop, but since it's guaranteed to have a value based on its natural flow, theWord
will be initialized.