Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not a NullPointerException while accessing static with null reference? [duplicate]

Here in following code we are getting value of i on a null reference, though a NPE is not there.

public class Test {
    static int i = 10;

    Test getTest() {
        return null;    
    }

    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.getTest());  
        System.out.println(t.getTest().i);
    }
}

output

null
10
like image 666
eatSleepCode Avatar asked Jan 21 '14 10:01

eatSleepCode


People also ask

Can a null reference be used to access a static variable?

A null reference may be used to access a class (static) variable without causing an exception. Even though the result of favorite() is null, a NullPointerException is not thrown.

When should we throw a NullPointerException?

NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.

Which of the following will cause a NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

How do I avoid NullPointerException?

How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.


1 Answers

Informally speaking, you can think of this

System.out.println(t.getTest().i);

as being equivalent to

System.out.println(Test.i);

because i is static.

This is the simplest answer probably.

Strictly speaking, they are not equivalent. Actually
getTest() is called but its return value is not used
for accessing the i field as this test below shows.

public class Test {
    static int i = 10;

    Test getTest() {
        System.out.println("Method getTest() called!");
        return null;    
    }

    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.getTest());  
        System.out.println(t.getTest().i);
    }
}
like image 56
peter.petrov Avatar answered Oct 13 '22 00:10

peter.petrov