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

前端 未结 3 1659
北恋
北恋 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:36

    What have you done for the variable x in the second code is called blank final variable. If a final variable is not initialized when it is declared, then it is known as a blank final variable.

    Many Java developers think that value of a final variable is known in the compile time. This is NOT always true. It is said that value of a blank final variable NOT known at the compile time. Hence your second code will give you a compile error. Compiler can see that you have initialized the final variable x, but compile doesn't know it's value. So compiler can't resolve the if statement. Therefor it thinks that variable y is not initialized.

    You can read more about Java final variables here.

提交回复
热议问题