This question already has an answer here:
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
Here
t
isn'tnull
as it has been initialized. Thus, you do not get aNullPointerException
.In next case where you expected a
NullPointerException
sincet.getTest()
returnednull
,i
is astatic
variable and you do not need to an instance to access static variables, you can just access them directly. Thus, you do not getNullPointerException
here too.And moreover,
i being a static variable, no instance is needed to get its value.