Contributing Editor

Unboxing Gotcha in Java

how-to
Aug 8, 20071 min

In a recent blog post, Java wiseman Norman Richards, points out that this innocent-looking line of code contains a gotcha that most IDEs (he checked Eclipse, I checked IntelliJ) don’t warn you about:

int sucker = thisMethodReallyReturnsAnIntegerNotAnInt();

Due to autoboxing (well, technically, unboxing), this code could set <font="courier">sucker</font> to null, which pretty much guarantees the dreaded NullPointerException.

What Richards doesn’t say is that this code is so innocent looking (and the bug possibility so little recognized), that almost no one would write a unit test for this assignment. At least, that is, until it blows up the first time.

Good catch. OK, back to work: Ctl-F “Integer”…