class Temp
{
public static void main(String[] args)
{
int x=10,y=20;
while (x<y)
{
System.out.println("Hello");
}
System.out.println("Hi");
}
}
输出 它打印 Hello infinity 次
但是当我将局部变量设置为 final int x=10,y=20; 然后它显示 Statement Unreachable
最佳答案
使这些变量成为 final
也使它们成为常量变量。这意味着编译器可以用变量的初始化值替换变量的使用。
因此,编译器会尝试生成以下内容
while (10 < 20)
这相当于
while (true)
这将使它成为一个无限循环,并且 block 之后的代码将变得无法访问。
这是在 Java 语言规范中指定的,here
A while statement can complete normally iff at least one of the following is true:
The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.
There is a reachable break statement that exits the while statement.
这些都不满足,所以while
语句不能正常完成。之后的所有内容都无法访问。
关于java - 为什么java final变量显示无法访问的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24176030/