-2

Getting NullPointerException, c1 is initialized in main method and is later accessed in class2, but i am getting NullPointerException

public class Test
{
    static Class1 c1;
    public static void main(String[] args) 
    {
        c1 = new Class1();    //c1 is initialized, still null pointer exception
    }  
}

public class Class1 
{
    int a,b;
    Class1()
    {
        class1();
    }
    void class1()
    {
        a = 5;
        b = 10;
        Class2 class2 = new Class2();
    }
}

public class Class2 
{
    Class2()
    {
        Class1 c = Test.c1;         //c1 is null here
        System.out.println(c.a);    //NullPointerException for Test.c1
        System.out.println(c.b);
    }
}

2 Answers2

1

To assign the value of Test.c1, you first need to construct completely an instance of Class1.

However, when you are constructing Class1, you call Class2 constructor into the class1() method, which in turns prints some stuff. At this point, you still didn't fully construct the Class1 instance, as a consequence, Test.c1 is not yet initialized

Maliafo
  • 153
  • 8
0

It's fairly straightforward:

  1. When Test is loaded, c1 gets its default value null.

  2. main gets called by the java tool.

  3. main calls Class1's constructor.

    1. Class1's constructor calls class1.

      1. class1 calls Class2's constructor.

        1. Class2's constructor tries to dereference Test.c1, which is null, so it throws.

It would only be once that nested series completed that c1 would receive a value. But since the code tries to use it before it has a (non-null) value, it fails.

Stepping through the code with a debugger can make this stuff dramatically clearer. Using a debugger is not an advanced skill, it's crucial for beginners, as a learning tool for what happens when.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875