Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an if/else if/else for a simple boolean not giving an "unreachable code" error

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;     } } 
like image 387
vvill Avatar asked Mar 18 '16 14:03

vvill


People also ask

Why are statements unreachable?

The Unreachable statements refers to statements that won't get executed during the execution of the program are called Unreachable Statements. These statements might be unreachable because of the following reasons: Have a return statement before them. Have an infinite loop before them.

How do you solve an unreachable statement?

If you keep any statements after the return statement those statements are unreachable statements by the controller. By using return statement we are telling control should go back to its caller explicitly .

How do you fix an unreachable error in Java?

1(a) is compiled, line 12 raises an unreachable statement error because the break statement exits the for loop and the successive statement cannot be executed. To address this issue, the control flow needs to be restructured and the unreachable statement removed, or moved outside the enclosing block, as shown in Fig.

Why does Java generate unreachable code errors during multiple catch statements?

When we are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e subclasses of Exception must come first and superclasses later. If we keep superclasses first and subclasses later, the compiler will throw an unreachable catch block error.


1 Answers

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.

like image 194
dejvuth Avatar answered Sep 27 '22 19:09

dejvuth