在while循环条件下为布尔基元获取无法访问的代码,但不能为布尔包装器获取代码

Lok*_*lor 1 java

题:

代码:

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

}
Run Code Online (Sandbox Code Playgroud)

输出:

.\com\logics\t4\_19_Tst.java:15: error: unreachable statement
        while (flag1) { System.out.println("this is unreachable code with compile error"); break;  }
                      ^
.\com\logics\t4\_19_Tst.java:17: error: unreachable statement
        while (flag5) { System.out.println("this is unreachable code with compile error"); break;  }        
                      ^
.\com\logics\t4\_19_Tst.java:19: error: unreachable statement
        while (flag3) { System.out.println("this is unreachable code with compile error"); break;  }        
                      ^
3 errors
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

可达性规则有许多,他们指的地方常量表达式与值truefalse

在您的代码中flag1flag3flag5都是常量表达式,因此它们的值用于可达性规则。

flag2flag4并且Boolean.FALSE恒定的表达式,并且不能是,因为常量表达式规则开始:

常量表达式是表示原始类型值或不会突然完成并且仅使用以下内容组成的字符串的表达式: [...]

Boolean既不是原始类型也不是String,因此类型的表达式Boolean永远不会被归类为常量表达式。(该规则可以很容易地被写入例如,它可能是,但这不是事情是这样的。)