Calling static method from a null reference in java

Reading Time: 2 minutes

When you start learning java, in no time you will learn what happens when you call a method on a null object.

NullPointerException ⚠

You will also know that static methods are called by class name. Though you can also call them by object reference. So one might wonder, what if we call the method with object reference, but the object is null?

Lets see, below a code snippet.

class Test {
	public static void print() { 
	    System.out.print( "hello"); 
	};
}

class Main {
	public static void main(String[] s) {
		execute(null);
	}

	public static void execute(Test t) {
		t.print();
	}
}

What do you think the output will be? By the definition of static methods, this code should work, right? And yes, it does. But how? If object is null, how will the run time know where that method comes from, because null doesn’t have any. So the answer is, the run time doesn’t need to know. Because, this is the job of compiler. It is one of the several optimizations that compiler performs on the code. In this case, by looking at the parameter type, compiler knows where the method comes from, and it then learns the method is static, so it resolves the type of object and replaces the code to call the method by its class name. Thus, run time only gets to see the class-name.

You can verify this by de-compiling the generated class file. Below is the de-compiled class file.

// 
// Decompiled by Procyon v0.5.36
// 

class Main
{
    public static void main(final String[] array) {
        execute(null);
    }
    
    public static void execute(final Test test) {
        Test.print();
    }
}

Leave a Reply