Tuesday 2 March 2010

The Terrible Dangers of Autoboxing (Part 1)

Below piece of code indicates why some manner of caution is called for when using ints and Integers interchangeably.

Can you tell what the code will do?

Can you tell what happens when Integer K = null?

public class Autoboxing
{

    public static void main(String [] testAutobox)
    {
        int j = 5;
        Integer K = new Integer(5);
        Integer L = new Integer(5);
        int m = 5;
        if (j == m)
        {
            System.out.println("j is equal to m");
        }
        if (j == K)
        {
            System.out.println("j is equal to K");
        }
        if (K == L)
        {
            System.out.println("K is equal to M");
        }
        if (K == m)
        {
            System.out.println("K is equal to m");
        }
    }

}
Addendum: Recently I got a weird problem when I was debugging in Eclipse. Apparently autoboxing doesn't work very well when trying to use expressions to evaluate in the Debugger. Perhaps Autoboxing, in this case, doesn't work, and the two objects are compared based on their memory address as is the default behaviour.

References

Most common gotchas in Java
http://vanillajava.blogspot.nl/2014/02/most-common-gotchas-in-java.html