JAW Speak

Jonathan Andrew Wolter

Can you spot Java Puzzler in this snippet?

without comments

Reading time: 2 – 2 minutes

I ran across this last week. It was marvelous when we saw what was happening, but entirely puzzling at first.

Boolean someFlag = complicatedLogicToFigureOutFlag();
Person person = new Person(someFlag);

Any signs for concern? How about if Person’s constructor is:

Person(boolean someFlag) {
    this.someFlag = someFlag;
}

Any warning signs?

Will it compile?

Read more for the full puzzler.

If you didn’t see a warning sign, but said it would compile — you’re half right. It will compile, but there’s a great big NullPointer waiting for you depending on the value of someFlag. Because autoboxing was a shim initially slid into Java 1.5, this will compile:

Boolean someFlag = null;
Person person = new Person(someFlag); // will compile, but then NPE ambiguously

But at runtime, it will fail ambiguously with a Null Pointer on the line of the constructor.

Of course, this will not compile:

Person person = new Person(null); // won't compile because signature is boolean

My pair and I saw this in a test with a particularly ugly constructor with 12 parameters. We were following Misko’s style of “use nulls in tests, but not in production code” and thus that Boolean was ending up as null. By binary search we identified which parameter caused the trouble, initialized it to false instead of null, and then shared our “Ah Ha!” moment with several other engineers around the office.

Should something like this be an interview question you ask a candidate? Maybe if they are doing great on all other fronts, and you’re curious how well they understand the intricacies of Java. But I don’t generally like obscure fact questions because in real life we just figure them out. So, yes I would use this in an interview where we are pairing, so I could watch the candidate troubleshoot.

Bookmark and Share

Written by Jonathan

September 30th, 2009 at 2:51 pm

Posted in code, java, puzzle

Leave a Reply