Does anyone know why:
public void foo()
{
System.out.println(\"Hello\");
return;
System.out.println(\"World!\");
}
Would be rep
This is to allow a kind of conditionally compilation.
It is not an error with if
, but the compiler will flag an error for while
, do-while
and for
.
This is OK:
if (true) return; // or false
System.out.println("doing something");
This are errors
while (true) {
}
System.out.println("unreachable");
while (false) {
System.out.println("unreachable");
}
do {
} while (true);
System.out.println("unreachable");
for(;;) {
}
System.out.println("unreachable");
It is explained at the end of JLS 14.21: Unreachable Statements:
The rationale for this differing treatment is to allow programmers to define "flag variables" such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.