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
continuestatement 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.)