Originally posted by Tony Morris:
Because 'true' is a constant expression (JLS 15.28).
Try this:
boolean b = true; // not a constant expression.
if(b){return;}blah(); // no complaints from the compiler.
final boolean b = true; // A constant expression.
if(b){return;}blah(); // compiler complains.
Actually, neither of those code samples cause a compile-time error, because there are special rules for "if" statements when it comes to unreachable statements.
The case where the compiler complains about the unreachable statement "blah();" is when it's a while loop, not an if statement, and the boolean
test value is a constant value. Both of the following two examples cause compiler errors:
And the following example compiles fine because the boolean test is not a constant expression: