为什么Java编译器不能理解这个变量总是被初始化? [英] Why does the Java compiler not understand this variable is always initialized?

查看:167
本文介绍了为什么Java编译器不能理解这个变量总是被初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Foo{
    public static void main(String args[]){
        final int x=101;

        int y;
        if(x>100){
            y=-1;
        }
        System.out.println(y);
    }
}

Java编译器理解if语句的条件总是为true,因此y将始终初始化。没有编译错误,如预期的那样。

Java compiler understands the condition of the if statement is always true and therefore y will always be initialized. No compile error, as expected.

class Bar{
    public static void main(String args[]){
        final int x;
        x=101;

        int y;      
        if(x>100){
            y=-1;
        }
        System.out.println(y);
    }
}

但是当我打破x的声明和初始化时两行,编译器似乎没有得到条件总是为真并且y将始终被初始化。

But when I break the declaration and initialization of x into two lines, the compiler does not seem to get that the condition is always true and y will always be initialized.

final int x;
x=101;
byte b;
b=x;
System.out.println(b);

此处发生同样的事情并且编译器会丢失精度错误。

Same thing happens here and the compiler gives a loss of precision error.

final int x=101;
byte b;
b=x;
System.out.println(b);

同样,编译器可以理解x在b的范围内。

Again, the compiler can understand that x is inside the range of b.

推荐答案

它与编译器如何确定是否将执行语句有关。它在 JLS#16 中定义:

It has to do with how the compiler determines if a statement will be executed or not. It is defined in the JLS #16:


当对其值进行任何访问时,每个局部变量和每个空白的最终字段必须具有明确赋值。

Each local variable and every blank final field must have a definitely assigned value when any access of its value occurs.

在您的情况下,编译器无法确定 y 已明确分配并为您提供错误。这是因为它需要确定条件始终为真,并且只有在 if 中的条件是常量表达式时才可能。

In your case, the compiler can't determine that y has been definitely assigned and gives you an error. This is because it would need to determine that the condition is always true and that is only possible if the condition in the if is a constant expression.

JLS#15.28 定义常量表达式


编译时constant表达式是表示基本类型的值的表达式或不突然完成的String,仅使用以下内容组成:

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:


  • [ ...]

  • 引用常量变量的简单名称(§6.5.6.1)(§4.12.4)。

JLS#4.12.4 常量变量定义为:


原始类型或类型String的变量,是最终的并使用编译时常量表达式初始化,称为常量变量。

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression, is called a constant variable.

在您的情况下, final int x = 101; 是一个常量变量,但是 final int x; x = 101; 不是。

In your case, final int x = 101; is a constant variable but final int x; x = 101; is not.

这篇关于为什么Java编译器不能理解这个变量总是被初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆