Can we call a static method with a null object in Java? If so, how?

The following code contains an example, in which a static method is called via a null reference.

public class Test {
    public static void main(String... args) {
        Test test = null;
        test.greeting(); // call with null reference
    }
    public static void greeting() {
        System.out.println("Hello World");
    }
}

Because Test::greeting is a static method, the expression test.greeting() is identical to Test.greeting(). For that reason, there is no NullPointerException thrown at runtime.

Leave a Comment