-1
`class test {
        int x = 10, y = 5;
        public static test t1 = new test();

        {
            System.out.println("NSB");
            System.out.println(t1.x);
            System.out.println(t1.y);
        }

        public static void main(String[] args) {
            System.out.println("C main");

        }

    }`
markspace
  • 10,621
  • 3
  • 25
  • 39
Coder
  • 9
  • 3

1 Answers1

3

Because the initialization block is executed before the constructor runs, and before the assignment to t1 is made.

So basically, this is executed first : new test() That invokes the constructor. Just before that constructor runs, the initialization block runs. That block dereferences test.t1, but no assignment has been made yet.

Thus, Calvinism NPE.

markspace
  • 10,621
  • 3
  • 25
  • 39
  • what do you mean by dereference. Could you please elaborate on that point? When the Constructor is invoked ideally there should be memory allocated for both x and y right? – Coder Apr 13 '20 at 20:47
  • "Deference" means to use a reference. `t1` is a reference to the object you are creating, and when you access it by `t1.x` you deference `t1`. It's `t1` that's the problem here, not `x`. Yes memory is allocated for `x` and `y`, but the `t1` has not been assigned yet (the `=` hasn't been executed yet) because you're still in the constructor (in other words `new` hasn't finished yet). – markspace Apr 13 '20 at 21:48