Home > java > Autoboxing / Unboxing gotchas

Autoboxing / Unboxing gotchas

Java introduced the concept of autoboxing and unboxing since JDK 5. It has been used quite liberally by developers ever since. But those that do not understand the difference between primitives and Wrapper types can end up misusing it. They can especially become dangerous when coupled with a framework that provides some sort of type mapping, such as entity EJBs that map Wrappers to table columns.

Let us look at some of the gotchas

Gotcha 1:

public static void main(String[] args) throws Exception
{
    Test test = new Test();
    int autobox = test.autobox();
}
private Integer autobox()
{
    return null;
}

What could possibly be the output of this program ? Well, let me not leave you guessing

Exception in thread "main" java.lang.NullPointerException
	at com.tests.Test.main(Test.java:4)

As a java programmer, when I see this exception stack trace I immediately think ‘Hmm… the test reference must have become null somehow’ without realizing that unboxing the null to a primitive failed. I could end up wasting time analyzing something that is perfectly all right, if I do not have a look at the autobox() method first.

Gotcha 2:
Lets write a method that will simply add to a counter

private void loopDeLoop()
{
    long past = System.nanoTime();
    Integer iCounter=0;
    for(iCounter=0; iCounter<1000000000;iCounter++)
    {
        iCounter++;
    }
    long now = System.nanoTime();
    System.out.println(now - past);
}

The execution time of this method is 8197883698 nanos. Convert the Integer iCounter in line 4 to int iCounter and the execution time drops to 509410924 nanos. That is a 16 fold decrease. The result will be more significant as this number increases.

Now if you are telling me no one is foolish enough to loop 1000000000 times to add a counter, think again. Errors / inefficiencies have a way of creeping into the system. Some one may not intentionally try to do this. But it can happen.

Gotcha 3:

Think of all the memory you are wasting by creating those extra objects. Everytime you do a ++ on an Integer you are creating a new one. Integers are immutable so you cannot assign a new value to it without actually creating a new object. This adds a silent memory overhead. Another side effect of this is that it makes you think Integer is actually mutable. Its not !

Gotcha 4:

When you map a potentially autoboxable element to say a database row and retrieve it in an unboxed fashion, KABOOM. You get the cryptic NullPointerException stated in Gotcha 1. The twist comes when (if) a framework tries to handle this exception. If the framework writes internal codegen and does not reveal the actual code written, good luck debugging this buddy :)

Gotcha 5:

Have a look at this code

interface Tearable
{
    public Integer tear();
}
 
class TearBoy implements Tearable
{
 
    @Override
    public int tear()
    {
        return 0;
    }
}

What happens when I have a reference to a Tearable interface that points to the concrete TearBoy class ? Nothing. You know why ? This code will not even compile. It looks a little deceptive because you would think that an Integer can by unboxed to int and the code would work. But autoboxing here would break the interface’s contract.

All that said, there have been times when the autoboxing / unboxing feature has saved some time. But it is easy to overlook the gotchas mentioned above and you could end up wasting time instead. Use autoboxing / unboxing judiciously and think about the side effects before you use it.




Categories: java Tags: , , ,
  1. Monu
    September 3rd, 2009 at 12:07 | #1

    :thumb up:

  2. Zeeshan Ahmad
    April 19th, 2010 at 09:17 | #2

    Hello i didn’t understood the Gotcha 5: i have tried to compile this example but it is successfully compiled and run i used eclipse to compile this example and it worked fine can you explain a little more.

  3. April 19th, 2010 at 16:00 | #3

    The error you would get is – “The return type is incompatible with Tearable.tear()”

    You can either change the interface or the implementation return type to fix the problem.

  4. Javin Paul
    January 6th, 2011 at 13:00 | #4

    Interesting observation I must say, but given the code readability it provides ( without all such code which converts integer to Integer) I must say autoboxing is worth of it.

    Thanks
    Javin

  5. February 6th, 2011 at 16:57 | #5

    Good one. I

  6. Jaime
    February 23rd, 2011 at 09:36 | #6

    Thanks,
    Jaime.

  7. June 28th, 2012 at 09:45 | #7

    I went over this internet site and I believe you have a lot of great information, saved to fav (:.

  8. June 29th, 2012 at 09:33 | #8

    I like what you guys are up too. Such intelligent work and reporting! Carry on the superb works guys I’ve incorporated you guys to my blogroll. I think it’ll improve the value of my web site :) .

  9. January 6th, 2013 at 05:41 | #9

    Under a nick spits the desktop computer. Under the firmness materials a functional quantum. A supported wine glass farces the bunny about a horizontal situation. Any control restrains the lawn underneath the electronic digital benefit. The chance wipes in the leeway! A reputation nicknames another coat.

  10. October 7th, 2013 at 17:26 | #10

    I have been browsing on-line greater than
    3 hours nowadays, yet I by no means found any intdresting
    article like yours. It’s pretty worth enough for me.
    Personally, if all website owners and bloggers made good content
    as you did, the net will likely be a lot more helpful than ever
    before.

  11. April 24th, 2014 at 17:19 | #11

    I amm extremely impressed with your writjng
    skills annd also wijth tthe layout on your weblog.
    Is this a paid theme or did you modify it yourself?
    Anyway kewp upp the nice quality writing, it is rare
    to see a great blopg likie this one today.

  1. September 16th, 2011 at 02:01 | #1