Why is an if/else if/else for a simple boolean not

2020-02-26 02:19发布

问题:

Why is this code not giving an "unreachable code" error? Since a boolean can only be true or false.

public static void main(String args[]) {
    boolean a = false;
    if (a == true) {

    } else if (a == false) {

    } else {
        int c = 0;
        c = c + 1;
    }
}

回答1:

From JLS 14.21. Unreachable Statements

It is a compile-time error if a statement cannot be executed because it is unreachable.

and

The else-statement is reachable iff the if-then-else statement is reachable.

Your if-then-else statement is reachable. So, by the definition the compiler thinks that the else-statement is reachable.

Note: Interestingly the following code also compiles

// This is ok
if (false) { /* do something */ }

This is not true for while

// This will not compile
while (false) { /* do something */ }

because the reachability definition for while is different (emphasis mine):

The contained statement is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.