There are tons of answers on StackOverflow related to the of usage break
statement in Java, yet unfortunately, I was not able to discover a clear explanation to my Java beginner type of a question.
// Main.java
public class Main {
public static void main(String[] args) {
foo: {
break foo; // compiles and executes OK
}
bar: {
// Java compiler produces an error at this point
break;
}
// perhaps Java compiler complains on unused label, but...
baz: {
System.out.println("Hello World"); // compiles and executes OK
}
}
}
javac Main.java
Main.java:10: error: break outside switch or loop
break;
^
1 error
What am I missing?
There are 2 forms of the break
statement, one without a label and one with a label.
Your first case compiles because there is a corresponding label of the same name labeling the statement to break from.
But in the second case, without a label, needs a specific kind of statement to break out of. According to the JLS, Section 14.15:
A
break
statement with no label attempts to transfer control to the innermost enclosingswitch
,while
,do
, orfor
statement; this enclosing statement, which is called the break target, then immediately completes normally.A
break
statement with label Identifier attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label; this enclosing statement, which is called the break target, then immediately completes normally. In this case, the break target need not be aswitch
,while
,do
, orfor
statement.It is a compile-time error if a
break
statement has no break target.
There is no enclosing switch
, while
, do
, or for
; a block doesn't meet this requirement, so there is no break target. Because there is no break target, there is a compiler error.
The break statement with an explicit label only requires a labeled statement, which can include a block with braces.