简体   繁体   中英

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

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; eg 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.

The continue is checking the boolean expression before actually continuing, as the manual says:

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

For more details have a look at: branching semantics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM