Why does the Java compiler not understand this variable is always initialized?

前端 未结 3 1690
北恋
北恋 2020-11-29 04:10
class Foo{
    public static void main(String args[]){
        final int x=101;

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


        
3条回答
  •  余生分开走
    2020-11-29 04:13

    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.

    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 defines constant expressions:

    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:

    • [...]
    • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

    The JLS #4.12.4 defines constants variables as:

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

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

提交回复
热议问题