题:
flag1, flag3& flag5AFAIK 在编译时本身解析变量值,因此它必须给出错误。
flag2, flag4& Boolean.FALSE: 为什么我们没有得到编译时错误?
找到 1 个参考,但不完全相同。
代码:
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)
输出:
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
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)