java - 为什么java final变量显示无法访问的语句

标签 java variables local final

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/

相关文章:

java - 安卓 : Could not GET/Find get repos from bintray. com

java - 如何在scala repl中加载和使用 native 库?

python - 变量赋值和修改(Python中)

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 通过本地存储增加值(value)

java - 如何在Android中使用Google Vision人脸检测API仅裁剪脸部而不是椭圆形的全身

java - (泛型)不能对非静态类型 T 进行静态引用

python - 创建单独变量字典的更简单方法?

facebook-graph-api - Facebook本币支付直接退款,无需开发商处理纠纷

java - 具体实现openGL和LWJGL中的局部旋转