The designated continue statement in the while loop

The following simple examples lead to a compile-time error. But it is not clear why.

public static void main (String[] args) throws java.lang.Exception { int i = 0; d: { System.out.println("d"); } while(i < 10){ i++; continue d; } } 

- and -

 public static void main (String[] args) throws java.lang.Exception { int i = 0; d: { System.out.println("d"); while(i < 10){ i++; continue d; } } } 

Demo

But the following works just fine:

 public static void main (String[] args) throws java.lang.Exception { int i = 0; d: while(i < 10){ { System.out.println("d"); } i++; continue d; } } 

Does it allow passing control to only one while , for or do statement? He does not speak in JLS . In fact, it says:

The continue statement labeled Identifier is trying to transmit (see ยง 14.7) that has the same Identifier as its label; This statement, which is called the continuation of target, immediately terminates the current iteration and starts a new one.

+6
source share
2 answers

A continue means go to the beginning of the loop. Therefore, when you continue on the label, the label should be in a loop. (This is not a goto statement ...)


Does it allow transferring control to only one, for or to make an expression? This does not say in JLS.

Actually, he really says.

Here is what JLS 14.6 (Java 8 version) really says:

"The continue statement with the label Identifier attempts to transfer control to the enclosed marked expression (ยง14.7), which has the same Identifier as its label, this statement, called the continuation target, then immediately ends the current iteration and starts a new one.

To be precise, the continue statement with the Identifier label always ends abruptly, so continue with the label identifier.

The continue target must be while, do, or for the statement, or a compile-time error occurs. "

(in bold in the original!)

The bold sentence says that the statement that the label is attached to (called "continue target") should be some kind of loop operation.

+5
source

JLS 14.16

The continue statement can only occur after some time, do or for statement (iterative statements) ;

The final target must be while, do or for, or a compile-time error occurs.


The continue statement labeled Identifier is trying to pass; control the inclusion of the labeled statement (ยง14.7) , which has the same Identifier as its label; this statement, which is called the continuation of target, and then immediately completes the current iteration and starts a new one.


The continue statement must reference the label within the layout method, constructor, or initializer. No non-local jumping. If without a label with an identifier as a label in the immediately including method, constructor, or initializer contains continue, a compile-time error occurs.

+3
source

Source: https://habr.com/ru/post/976713/


All Articles