I'm studying for a Java exam and came across the "unreachable statement" compiler error, e.g:
Source.java:10: error: unreachable statement
System.out.println("This code is not reachable");
Am trying to understand when this would or wouldn't happen - e.g. it doesn't happen for these cases:
// Case #1
if (true) {
System.out.println("This code is reachable");
} else {
System.out.println("This code is not reachable"); // Compiles OK
}
// Case #2
for (i = 0; i < 5; i++) {
if (true) continue;
System.out.println("This code is not reachable"); // Compiles OK
}
It seems the compiler isn't smart enough to detect when the if condition is constantly true - could someone provide a more detailed explanation?
From the Java Language Specification, 14.21. Unreachable Statements (emphasis by me):
So while the code is indeed unreachable, the compiler explicitly does not regard it as such. The reason stated is to allow programmers to define "flag" variables such as
It should be possible to switch
DEBUGbetweenfalseandtruewithout having to change anything else in the code (due to compilation errors).