If you are new to Java 5 and have been running into mysterious null pointer exceptions, then you may find Burt Beckwith's
blog enlightening. In the entry Burt explains what he did to locate and eliminate a mysterious null pointer exception
Burt was relying on autoboxing
to allow him to use the primitive type int as keys in a map when he made this discovery.
I spent a while earlier today debugging a very small block of code that was throwing a NPE. There were few options for instances that could be null, but since I was looking in the wrong place for the problem, it took longer than it should have to fix
Autoboxing has been designed to address the inability to mix objects and primitives in the Java language. What Burt was trying to do was store primitive values in a Map. Since both the key and value pairs must be objects, primitives must be wrapped before you can save them. Prior to Java 5, this meant doing something map.put( new Integer( integerKey), value). With Java 5 auto-boxing comes to the rescue so that we can now do; map.put( integerKey, value). The magic is the compiler will add in all the stuff needed to create the wrapper.
Under the hood when you autobox and treat an Integer as an int or vice versa, the compiler inserts a call to intValue()
The difficulties comes when you need to map back to an integer. You may have a 0 or you may have a null. However since 0 is meant to represent both the designers had to make a choice and they choose null. The inject code to support auto-boxing looks something like this;
Integer z = Integer.valueOf(5);
Integer i = null;
int j = i.intValue();
The result can be a hidden NPE.