Search code examples
javamultithreadingnullnullpointerexceptionoperation

Force method call on null variable to throw a NullPointerException


Possible Duplicate:
How come invoking a (static) method on a null reference doesn’t throw NullPointerException?
Static fields on a null reference in Java

I tried the code from this old video:

class Impossible {
    public static void main(String[] args) {
        Thread t = null;
        System.out.println(t.currentThread().getName());
    }
}

Output: main

Well, just what the heck is that?! Does java.lang.Thread breach any the NullPointerException rule?

But what I'm most interested in it: How can I make that variable behave to throw a NullPointerException?


Solution

  • Does java.lang.Thread breach any the NullPointerException rule?

    No, reason for a NPE been thrown is not related to a class. It is related to an instance of that class, on which invocation is done. Also, it depends upon which type of method, or field you are accessing.

    What is happening here is, currentThread() is a static method of Thread class. Which is boudn to a class, rather than an instance. So, even if you invoke it on a reference of Thread class, it is actually invoked on class name.

    So,

    Thread t = null
    t.currentThread();
    

    is actually invoked as: -

    Thread.currentThread();
    

    So, when accessing a static member through an object reference expression, only the declared type of the reference matters. This means that:

    • It doesn't matter if the reference is actually pointing to null, since no instance is required.

    • If the reference is not null, it doesn't matter what the type of the object the reference is pointing to, there is no dynamic dispatch.


    How can I make that variable behave to throw a NullPointerException?

    Well, the current print statement will never throw a NPE. The first part is already explained above. Now, let's move ahead.

    Thread.currentThread();
    

    The above invocation will never return null. It always returns the current thread instance. And in Java, you are always inside one or the other thread. Even when inside public static void main method, you are executing the Main Thread. So, currentThread can't be null.

    And hence, further invocation: -

    Thread.currentThread().getName();
    

    will work fine, and return the name of current thread.