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;
	}
}

19 Responses to “Unboxing as a Java Interview Question”  

  1. Gravatar Icon 1 Dim

    I would rather prefer to not have primitives at all and let a compiler to do “real” unboxing instead. This way the compiler might decide between an wrapper object (Integer) or int.

  2. Gravatar Icon 2 stephan

    @Dim: Me too.

  3. Gravatar Icon 3 Casper Bang

    @Dim: Completely agree. A simpler type system which would fix a loooot of issues.

  4. Gravatar Icon 4 jonathan

    I might not have spotted that either. But I also would never write:

    int i2 = i1;

    when

    int i2 = i1.intValue();

    …works perfectly fine. While this can still throw a NPE, atleast it’s easier for the person reading the code. No magic is involved here.

    The point of autoboxing is to make it easier to use primitives with collections.

    // Insert 10 #’s
    for (int i = 0; i < 10; i ) {
    list.add(i);
    }

    int sum = 0;
    try {
    for (int val : list) {
    sum = val;
    }
    } catch (AutoUnboxingException ex) {
    // sum = ??
    }

    With your AutoUnboxingException it’s now more verbose than not having autoboxing at all. The Integer’s will never be null because you used boxing to store them into the collection. I probably missed the point of your post. I don’t like interview questions that misuse language features than ask “what’s wrong!?” :)

  5. Gravatar Icon 5 stephan

    @Jonathan: You’re right. But usually it isn’t as easy as

    int i2 = i1;

    to spot the error. Sometimes it’s a method call.

    callMethodWhichHasIntWithInteger(i1);

    Your

    for (int val : list)

    will throw a NPE if a val in the list is NULL, and hard to spot too.


    } catch (AutoUnboxingException ex) {

    would be an UncheckedException just like an NPE, so no noise there.

    “The Integer’s will never be null because you used boxing to store them into the collection.”

    If you control the insertion in your class, yes. If you’re method takes collections from somewhere else, then no.

    “I probably missed the point of your post. “

    Most people probably have if they haven’t chased an NPE around for some time which is caused by unboxing.

    “I don’t like interview questions that misuse language features than ask “what’s wrong!?” :)”

    In which way did I misuse the feature?

  6. Gravatar Icon 6 jonathan

    Well I’ve never encountered that specific issue but like I said I never use unboxing to convert an Integer to an int in a generic case. Since I always use .intValue() to convert to primitives in the generic case, it’s usually pretty easy to spot the NPE.

    I see your point about the method call. IMHO, that’s just bad programming though. Autoboxing allows people not familiar with Java to do those sorts of things - I see this quite often where int’s and Integers are used interchangeably by non software guys. I do see the advantage of the autounboxingexception though. It would definitely be easier to track down the error.

  7. Gravatar Icon 7 stephan

    To shorten your comments in a post about unboxing:

    “I never use unboxing to convert an Integer to an int in a generic case. […] I probably missed the point of your post.”

    Probably ;-)

  8. Gravatar Icon 8 french_c

    I am not sure whether this is a good interview question or not. Maybe it’s because I usually don’t hire this kind of people.

    Anyway: Should we discuss micro architecture while looking into Radeox or SnipSnap code? ;)

  9. Gravatar Icon 9 stephan

    french_c: Why don’t you think it isn’t a good idea to talk about Exception design (for which the unboxing question usually is an entry point)?

    Oh, Radeox is quite ok, I can live with it, SnipSnap. Well. And both don’t have a good exception design.

  10. Gravatar Icon 10 french_c

    It’s not so much about being a good or bad idea. It’s more about the kind of people and the kind of skill you are looking for. While I always enjoy having experienced (Java-) developers in my team I tend to believe the importance of language level knowledge is overestimated. I would even say that in most cases the importance of lower level programming skills is overestimated (especially if this is the only qualification you are interested in).

    If I have to choose between someone with basic programming skills who understands the importance of communication and the importance of business requirements OR someone with (very) good programming skills who tends to avoid direct communication with their ‘customers’ and team members I would always choose number one. This is because I believe programming style and programming skills are more or less a team issue. Therefore it can be trained - while missing social skills (and pattern) can’t.

    Of course this implies that you have at least one experienced team member who likes to teach and train (and management supports that strategy).

    So the unboxing (or better defensive design and programming) question might be a good question for your key (infrastructure) developers. And even in these cases I look for other - more important - skills first. Why? Because I believe even design philosophies depend your existing team members and require good social skills of your key architects/developers.

    Disclaimer: I have to deal with typical business applications day by day. Everything I said might not apply for other types of software.

  11. Gravatar Icon 11 stephan

    @french_c: Well when your development is Java-only it’s usually a good idea to hire Java developers.

    But beside that getting someone to know how he does error handling - in my opinion - has nothing to do with Java but with design and thinking skills -especially thinking about your co-developers who need to work with your code. So in the end perhaps it’s mostly about social skills.

    “[…] importance of communication […]”

    Excactly. But discussing Exception handling with me, and thinking about other developers, is about communication skills. Defending his choice, making concessions, seeing my points is all about communication.

    So I cant’ see this as a Java question or “lower level programming skills” but more about thinking skills, communication skills, design skills and social skills.

  12. Gravatar Icon 12 french_c

    ” … So I cant’ see this as a Java question or “lower level programming skills” but more about thinking skills, communication skills, design skills and social skills.”

    It still remains a somewhat low-level entry point for a high level discussion. I usually prefer a top down discussion, while your question indicates a bottom up approach to me. (I might be wrong, though).

    So nowadays I start a second interview with a larger piece of code (such as the famous tomcat DefaultServlet) or a typical non-technical customer requirement. There might be a good chance we end up in a low-level discussion, but it’s up to the applicant whether we talk about requirements, software design and/or low-level implementation details.

    It seems my interview strategy (that pretty much reflects our day-to-day business) makes it difficult to talk about low-level issues. And due to our business low-level focus isn’t always a plus.

    I think we simply use two different strategies to reach the same goal;).

  13. Gravatar Icon 13 stephan

    “I think we simply use two different strategies to reach the same goal;).”

    Think so too. We two talked about the DefaultServlet question some years ago, but I forgot. Might be good to try :-)

  14. Gravatar Icon 14 Torgny Andersson

    The fact that int i = someIntegerObject; can throw NullPointerException is a classical example of leaking abstraction. The java people tried to make Integer behave like an int, but failed (too bad (for us)). I think that primitive types like int, double, and byte[], are more or less a bug in the language. A better approach is to treat everything equally… that is, everything is an object.

    Of course, the compiles could optimize an Integer into an int if that is needed, but to a developer there should be no difference.

    I totallt agree that NullPointerException shoud not be thrown when auto-unboxing fails… AutoUnboxingException (which, fo course, inherits from NullPointerExeption) is much better.

    I must say that the more I use Java, the more I dislike Java as a language. On the other hand, the more I use Java, the more I like Java a platform (the JVM, and all the available tools, etc).

  15. Gravatar Icon 15 Torgny Andersson

    Sorry, what I meant to say was that AutoUnboxingException inherits from RuntimeException.

  16. Gravatar Icon 16 stephan

    @Togny: You’re right, I forgot about Joels leaky abstractions. Yes, int should go out.

  17. Gravatar Icon 17 Torgny Andersson

    We agree yet again. :)

  18. Gravatar Icon 18 William

    I have a reasonable amount of experience setting supervision questions for undergraduates, where the goal is similar: eliciting the student’s/interviewee’s understanding of programming. Generally, I’ve interview questions like the one you posed to be very bad questions because they are anti-cooperative. To avoid giving away the answer, you have framed a very ambiguous first question (”what can happen”) and the whole thing turns into “can you guess what I happen to want to talk about now, even though I’m trying to keep it secret?” Many of your interviewees will assume that “do some stuff with i1″ implies that the missing code is what instantiates i1 — that is not a lack of Java knowledge, just a communication discrepancy about what your elided code intends to convey. Some of the rest will spot the problem but still not tell you because they don’t know they are being asked to find error with your code (you said “what can happen” not “what’s wrong with this”), and they feel they need permission to tell the interviewer he has done something wrong. If you just plain asked “could this give an NPE?” those same interviewees might well answer “yes, because the compiler will substitute code dereferencing i1, which could be null”.

    So generally, I find these questions select for “how well do you understand how artificial interview questions work?” rather than “how well do you understand the programming language”.

  19. Gravatar Icon 19 stephan

    @William: Good points, I’ll think about them and incorporate my thoughts in my future questions.

Leave a Reply



RSS