Unboxing as a Java Interview Question

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

Integer i1;
... 
// do some things with i1;
...
int i2 = i1;

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

int i2 = i1;

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.

public class Test {
	
	public static void main(String[] args) {
		if (isSomething()) {
			System.out.println("Something!");
		}
	}
	
	public static Boolean isSomething() {
		return null;
	}
}

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me