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.
Welcome to GeeksforGeeks!!
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:
- 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 GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
- Method overloading and null error in Java
- Calling an External Program in Java using Process and Runtime
- Null Pointer Exception In Java
- Interesting facts about null in Java
- Replace null values with default value in Java Map
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java lang.Long.builtcount() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.lang.Short toString() method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples