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
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.
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.
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 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.
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. ActuallygetTest()
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With