Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do-while loops with continue and with and without a label in Java

Tags:

java

do-while

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?

like image 974
Lion Avatar asked Dec 25 '11 15:12

Lion


2 Answers

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

like image 136
Stephen C Avatar answered Oct 12 '22 23:10

Stephen C


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.

like image 44
Matt Ball Avatar answered Oct 13 '22 01:10

Matt Ball