Wednesday, July 3, 2024
HomeLanguagesJavaCalling a method using null in Java

Calling a method using null in Java

Prerequisite: null in Java, Static in Java

Can you predict the output of the following program??
Before answering, please observe the fact that in given code, fun() is a static member that belongs to the class and not to any instance.




// Java program to illustrate calling
// static method using Null
public class GFG {
    public static void fun()
    {
        System.out.println("Welcome to Lazyroar!!");
    }
  
    public static void main(String[] args)
    {
        ((GFG)null).fun();
    }
}


Output:

Welcome to Lazyroar!!

Explanation:
This program looks as though it is ought to throw a NullPointerException. However, the main method invokes the greet method (fun) on the constant null, and you can’t invoke a method on null.
But, when you run the program, it prints “Welcome to Lazyroar!!”. Let’s see how:

  • The key to understanding this puzzle is that GFG.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.

This article is contributed by Shubham Juneja. If you like Lazyroar and would like to contribute, you can also write an article using contribute.neveropen.co.za or mail your article to contribute@neveropen.co.za. See your article appearing on the Lazyroar main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments