Let's look at the following do-while
loop. It's quite obvious and there is no question about it.
do
{
System.out.println("Hello world");
break;
} while(false);
It's quite obvious and just displays the string Hello world on the console and exits.
Now, the following version of do-while
seems to be getting stuck into an infinite loop but it doesn't. It also displays the string Hello world on the console and exits silently.
do
{
System.out.println("Hello world");
continue;
} while(false);
Let's see yet another version of do-while
with a label as follows.
label:do
{
System.out.println("Hello world");
continue label;
} while(false);
It too displays the message Hello world on the console and exits. It's not an infinite loop as it may seem to be means that all the versions in this scenario, work somewhat in the same way. How?
The continue
statement means "proceed to the loop control logic for the next iteration". It doesn't mean start the next loop iteration unconditionally.
(If anyone wants to refer to the JLS on this, the relevant section is JLS 14.16. However, this part of the specification is a bit complicated, and depends on the specifications of other constructs; e.g. the various loop statements and try / catch / finally.)
Just like with a for
loop, the while
conditional in a do-while
is always checked before entering the loop body (after the first pass through, of course). And, just like with a for
loop, continue
never causes the termination expression to be skipped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With