Tuesday, August 07, 2007

Autoboxing == !Cool

So you're finally getting used to the idea of Java 5's "feature" of converting between primitive types and their corresponding object wrappers (e.g., int -- Integer). You're getting to the point where you kind of trust it. You're even getting to the point where you kind of rely on it. Life is good.

Then you go too far and try something weird and exotic like, oh, I don't know:

int sucker = thisMethodReallyReturnsAnIntegerNotAnInt();

No squiggly red line in your Eclipse editor. Cool! That must mean this will work! Because Java has static typing, and you can count on that! Yea you!

The problem is, it will work. It will work very nearly all the time. It will work until your method returns a null instead of an actual Integer. At which point you'll get a NullPointerException buried in your Struts 2 / OGNL / JSP project's Eclipse console stack trace, followed by a two-hour detour into the debugger wondering what the heck is going on. I mean after all, your code compiled, right? It worked for the first hour, right? Static typing is good, right? Autoboxing works, right?

Not that you're bitter.