The Wayback Machine - https://web.archive.org/web/20200130120955/https://www.geeksforgeeks.org/calling-method-using-null-java/amp/

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

Output:



Welcome to GeeksforGeeks!!

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 GeeksforGeeks!!”. Let’s see how:

This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks 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.



Article Tags :
Practice Tags :