Autoboxing In Java & Bug Patterns

Posted on February 4, 2009

Consider the following example:

1) Some Java Bean:

public class SomeBean implements Serializable {
   private int someInt;

   public int getSomeInt() {
      return this.someInt;

   public void setSomeInt(int someInt) {
      this.someInt = someInt;       

2) And somewhere in some class (with business logic), you have this:

HashMap<String, Integer> someMap = new HashMap<String, Integer>();

...and somewhere down the line, you find a code statement like this:


The above code statement works fine, when there are no 'null' values. But if there is a null value for some key, it fails.....because 'AutoBoxing' throws a NullPointerException when the above code statement tries to unbox a 'null' value.

So, the immediate solution for that would be something like:

Integer someInt = someMap.get("someString");

someBeam.setSomeInt((someInt != null) ? someInt : 0);

Blog Categories
The views expressed on this blog are my personal views and do not reflect the views of my employer or campaigns I am supporting.

All sample code is provided for illustrative purposes only. These examples have not been thoroughly tested under all conditions. The writer therefore, cannot guarantee or imply reliability, serviceability, or function of these programs.

All programs contained herein are provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.