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

JavaBooleanUnreachable Code

Java Problem Overview


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;
	}
}

Java Solutions


Solution 1 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvvillView Question on Stackoverflow
Solution 1 - JavadejvuthView Answer on Stackoverflow