Again fallen into java puzzler trap– Another Java Puzzler


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.

11 thoughts on “Again fallen into java puzzler trap– Another Java Puzzler”

    1. 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.

  1. 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 + “]”);

  2. 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. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: