I wrote this program in Java
public class Why { public static void test() { System.out.println("Passed"); } public static void main(String[] args) { Why NULL = null; NULL.test(); } }
I read that invoking a method on a null
object causes NullPointerException
, and yet the above program doesn't? Why is this? Am I not understanding something correctly?
If you call a static method on an object with a null reference, you won't get an exception and the code will run. This is admittedly very misleading when reading someone else's code, and it is best practice to always use the class name when calling a static method.
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
You can call a static method on a null pointer. The pointer will naturally be completely ignored in a static method call, but it's still a case when something that (without looking at the class definition) seemingly should cause a NullPointerException runs just fine.
It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.
test()
is a static
method. A static
member belongs to the type, and do not require an instance to access.
A static
member should ONLY be accessed via a type expression. That is, you should've written it as follows:
Why.test(); // always invoke static method on the type it belongs to!
Java does allow you to access a static
member via an object reference expression, but this is VERY misleading, since this is NOT the actual semantics of a static
member access.
Why aNull = null; aNull.test(); // DO NOT EVER DO THIS! // invokes Why.test(), does NOT throw NullPointerException
When accessing a static
member through an object reference expression, only the declared type of the reference matters. This means that:
null
, since no instance is requirednull
, it doesn't matter what the runtime type of the object is, there is no dynamic dispatch!!!As you can see, the exact opposites are true on both points for instance member access. This is why static
members should NEVER be accessed in a "non-static
" way, because it gives a very misleading appearance on what it's actually doing.
this
is crucial!)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