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?