Java / Methods
Can we invoke a static method on a null object reference in Java?
Yes. The compiler optimizes the code to invoke the static method using null object reference since object instance is not required to invoke a static method.
public class StaticMethodUsingNull { static void printWelcomeMessage() { System.out.println("Welcome to javapedia.net!"); } public static void main(String[] args) { StaticMethodUsingNull myRef = null; myRef.printWelcomeMessage(); /*Message will be printed sucessfully*/ } }
In case of calling a non-static (instance) method using null object reference, it will throw NullPointerException.
More Related questions...