Unboxing as a Java Interview Question

Sometimes I ask an unboxing question during Java interviews. “What can happen with unboxing? See this code:”

The thing that can happen is that i1 is NULL which will result in a NullPointerException being thrown.

“What is the problem with the NPE here?” There are several ones. The big one is that developers search for dereferencing variables (think “.”) when seeing a NPE. The line

does not have a dot, the trained eye of a Java developer has problems to see the NPE there (if he didn’t encounter the bug before).

“What would you have done instead, if you would have been the Sun developer designing the unboxing feature?”

Possible answers are:

  • Set i1 to the default value if i2 is null, 0 in this case (null being the default value for Integer)
  • Throw an IllegalArgumentException
  • Throw a ClassCastException
  • Throw an AutoUnboxingException (my favorite)

It’s more about discussing design and programming decisions than getting the right answer from the candidate. With questions like this you can see how defensive a programmer can think, how he writes maintainable code and how good his micro-architecture design skills are. Often there is a dialog between the candidate and me about good design, error handling, exception handling and error messages.

What would you do?

Thanks for listening.

As ever, please do share your thoughts and additional tips in the comments below, or on your own blog (I have trackbacks enabled)

Update: This code will throw an NPE too – obviously – but from reading the isSomething() line in a large app it might not be that obvious.

Comments are closed.