Open In App

Calling a Method Using null in Java

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, when we try to call a method using a null reference, we normally expect a NullPointerException. That is because there is no actual object to call the method. But here in this article, we will discuss how calling a method with null does not break the code.

Prerequisite: Before continuing to the article, make sure you have a good understanding of the following concepts:

Java Program to Call a Method Using “null”

Now, let us look at the code below. Can you predict the output of the following program?

Before answering, please observe the fact that in the given code, fun() is a static member that belongs to the class and not to any instance.

Illustration:

Java
// Java program to illustrate calling
// static method using null
public class Geeks {
    public static void fun() {
        System.out.println("Welcome to GeeksforGeeks!");
    }

    public static void main(String[] args) {
        
        // Calling static method using null
        ((Geeks)null).fun();  
    }
}

Output
Welcome to GeeksforGeeks!

Explanation: Even though it looks like we are calling a method on a null object. But, the main method invokes the greet method (fun) on the constant null, and you cannot invoke a method on null.
But, when you run the program, it prints “Welcome to GeeksforGeeks!”. Let’s see how:

  • The key to understanding this puzzle is that Geeks.fun is a static method.
  • Although, it is a bad idea to use an expression as the qualifier in a static method invocation, but that is exactly what this program does.
  • Not only does the run-time type of the object referenced by the expression’s value play no role in determining which method gets invoked, but also the identity of the object, if any, plays no role.
  • In this case, there is no object, but that makes no difference. A qualifying expression for a static method invocation is evaluated, but its value is ignored. There is no requirement that the value be non-null.

What Happens If Not Static?

Let us modify the method and remove the static keyword:

Java
public class Geeks {
    public void fun() {
        System.out.println("Hello from instance method");
    }

    public static void main(String[] args) {
        
         // Now calling instance method with null
        ((Geeks)null).fun();
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException

Explanation: When a method is not static, Java expects an actual object to call the method. Here, we are using null, there is no object to operate on, so the program throws a NullPointerException.



Article Tags :
Practice Tags :

Similar Reads