Why attempt to print uninitialized variable does not always result in an error message

前端 未结 6 1856
滥情空心
滥情空心 2020-12-24 10:28

Some may find it similar to the SO question Will Java Final variables have default values? but that answer doesn\'t completely solve this, as that question doesn\'t directl

6条回答
  •  無奈伤痛
    2020-12-24 11:06

    Ok, here is my 2 cents.

    We all know that final variables can be initialized only While declaring or later on in constructors. Keeping that fact in mind, let see what happened here so far.

    No errors Case:

    So when you use inside a method, it have already a value.

     1) If you initialize it, that value.
     2) If not, the default value of data type. 
    

    Error case :

    When you do that in an initialization block, which you are seeing errors.

    If you look at the docs of initialization block

    {
        // whatever code is needed for initialization goes here
    }
    

    and

    The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

    In compiler's eye, your code is literally equals to

    class HelloWorld {
    
        final int x;
        HelloWorld() {
            System.out.println(x);  ------------ ERROR here obviously
            x = 7;
            System.out.println(x);  
            System.out.println("hi");
        }
    
        public static void main(String[] args) {
            HelloWorld t = new HelloWorld();
        }
    }
    

    You are using it before even initializing it.

提交回复
热议问题