Why does this method call on a null object run without a NullPointerException?
This is because greet()
is a static method. So
((Null)null).greet();
is equivalent to,
Null.greet()
Since greet
is a static method, a class instance is not needed (and not used...) to invoke it.
The ((Null)null)
expression doesn't dereference null
, it simply serves as a type definition used to access the static method.
When we attempt to use an object reference that has a null value, NullPointerException
is thrown. So, in your example you may think that how greet()
method is successfully called from a null object.
But, look at the method signature carefully, it has a static
modifier in front of it. If you call a static method on an object with a null reference, you won’t get an exception and the code will run without any exception. That is because static methods are the class methods not the instance method.
So when you compile your code, ((Null)null).greet()
is simply converted to Null.greet()
.
For simplicity, consider the code below:
Null obj1 = null;
Null obj2 = new Null();
obj1.greet();
obj2.greet();
As greet()
is a static method here, during that method call compiler will simply ignore if there is anything inside the object created from it or not. It will be just compiled as Null.greet()
for both obj1
and obj2
.
However, try to remove the static
modifier from the method. You will find that NullPointerException
you were expecting.