首页 > 解决方案 > 为什么我在这个 java for 循环中没有收到错误?

问题描述

在下面的语句中,我们将得到无法访问的语句错误。我知道该错误背后的原因是什么。

for(;false;)
System.out.println("Unrechable statement");

我的问题是为什么我们不会在下面的声明中出错。

boolean b = false;
for(;b;)
System.out.println("NO error");

标签: java

解决方案


The reason is compiler will consider that there may be a chance that b is being changes from its previous value to some other value by some other part of your program or thread, Even though your program is not actually changing b but compiler will not detect it at compile time. Clarification could be just make b as final & see you will get the same error because compiler will notice that b is final & can not be changed by other part of program so will consider false as final value of b & thus will produce error .

final boolean b = false;
for(;b;)
System.out.println("NO error"); //error: unreachable statement


推荐阅读