Intent of My Blog
Today, while writing a piece of code, i found that i have again fallen into a java trap.This is a java puzzler that i read in java puzzler book.
What is the output of this java puzzler?
public class JavaPuzzler { public static void main(String[] args) { JavaPuzzler javaPuzzler = null; System.out.println(javaPuzzler.get()); } private static String get(){ return "i am a java puzzler"; } }
Before reading the answer ,please try running this in eclipse and see whether you got it correct.
Solution
You might think that it should throw NullPointerException because the main method invokes get() method on local variable which is initialized to null, and you can’t invoke a method on null.
But if you run this program, you will see that it prints “i am a java puzzler” . The reason is that get() is a static method.
Exactly, many will not notice the static method call.
System did what you wanted (call static method). Why is it a trap?
Regards,
Slava Imeshev
It is a trap because a developer may thing that he is calling a method on object which does not point to any object i.e. it is null, so you should get NullPointerException but you are calling a static method.
the simple solution is better overall coding style:
1. never assign at declaration time
2. always use final variables (you have to ponder a bit how to make sure the variable is initialized
with 1: if you hadn’t set your javaPuzzler to null, you would had got a compiler error.
the second helps you structure your code so that you’ll never have to do another “fail-safe” null check.
if you find yourself in a situation where the only to initialize a variable is to set it null you need to ask yourself “has this method then been called with bad parameters?”. if the answer is yes:
throw new IllegalArgumentException(“this is a helpful exception message; i cannot do anything with the parameter xyz=[” + xyz + “]”);
That wasn’t a difficult one 🙂
This one is in the book, puzzler 54 “Null and Void”, you should get yourself a copy (http://www.javapuzzlers.com) Also Eclipse will probably issue a warning when you invoke a static method on an instance, IDEA surely does.
Yes, you are correct that eclipse will tell you this problem.
Quite good trap. But i could not get the reason.
Please explore a bit.
Thanks,
Tanzy.
Too simple 🙂
At first sight, the static method is not obvious. that may be because of the method get() defined after the main method. So, it is easy to think that the code will throw an NullPointerException. But, if the static method get() was defined prior to the main method, we would have noticed the static method first, thus would be making correct guess. 🙂
That’s why a proper IDE marks this as warning – “static method invocation using an instance.”