Skip to content
Advertisement

Getting unreachable code for boolean primitive but not for Boolean wrapper in while loop condition

Question:

Code:

public static void main(final String[] args) {
    final boolean flag1 = false;

    final Boolean flag2 = Boolean.parseBoolean("false");

    final boolean flag3 = !true;

    final Boolean flag4 = 100 == 20;

    final boolean flag5 = 10 >= 20;

    while (flag1) { System.out.println("this is unreachable code with compile error"); break;  }

    while (flag5) { System.out.println("this is unreachable code with compile error"); break;  }        

    while (flag3) { System.out.println("this is unreachable code with compile error"); break;  }
    
    while (flag2) { System.out.println("this is uncreachable code without compile error"); break;  }

    while (flag4) { System.out.println("this is uncreachable code without compile error"); break;  }

    while (Boolean.FALSE) { System.out.println("this is uncreachable code without compile error"); break;  }

}

Output:

.comlogicst4_19_Tst.java:15: error: unreachable statement
        while (flag1) { System.out.println("this is unreachable code with compile error"); break;  }
                      ^
.comlogicst4_19_Tst.java:17: error: unreachable statement
        while (flag5) { System.out.println("this is unreachable code with compile error"); break;  }        
                      ^
.comlogicst4_19_Tst.java:19: error: unreachable statement
        while (flag3) { System.out.println("this is unreachable code with compile error"); break;  }        
                      ^
3 errors
java version "1.8.0_261"
Java(TM) SE Runtime Environment (build 1.8.0_261-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.261-b12, mixed mode)

Advertisement

Answer

The reachability rules have a number of places where they refer to constant expressions with a value of true or false.

In your code, flag1, flag3 and flag5 are all constant expressions, so their values are used in the reachability rules.

flag2, flag4 and Boolean.FALSE are not constant expressions, and can’t be, because the constant expression rules start:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following: […]

Boolean is neither a primitive type nor is it String, therefore an expression of type Boolean will never be classified as a constant expression. (The rules could easily have been written such that it could be, but that’s not the way it is.)

Advertisement