How to call a method using null in Java?

Prerequisite: null in Java, Static in Java

 
Before answering, please observe the very fact that in a given code, fun() may be a static member that belongs to the category and to not any instance.
 
// 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();
	}
}

Output:

Welcome to GeeksforGeeks!!

Explanation:

This program looks as if it needs to throw a NullPointerException. However, the most method invokes the greet method (fun) on the constant null, and you can’t invoke a way on null.
But, once you run the program, it prints “Welcome to GeeksforGeeks!!”. Let’s see how:

  • Although it's a nasty idea to use an expression because of the qualifier during a static method invocation, that's exactly what this program does.
  • Not only does the run-time sort of the thing referenced by the expression’s value play no role in determining which method gets invoked, but also the identity of the thing, if any, plays no role.
  • In this case, there's no object, but that creates no difference. A qualifying expression for a static method invocation is evaluated, but its value is ignored. there's no requirement that the worth be non-null.
 

Submit Your Programming Assignment Details