Differences between new Integer(123), Integer.valueOf(123) and just 123

MicNeo picture MicNeo · Jan 27, 2012 · Viewed 51.9k times · Source

Recenlty I saw code (Java) like this:

myMethod(new Integer(123));

I am currently refactoring some code, and there is a tip in Sonar tool, that it's more memory friendly to use sth like this:

myMethod(Integer.valueOf(123));

However in this case, I think that there is no difference if I would use:

myMethod(123);

I could understand that, if I would pass a variable to the method, but hard coded int? Or if there would be Long/Double etc and I want Long representation of number. But integer?

Answer

Marcelo picture Marcelo · Jan 27, 2012

new Integer(123) will create a new Object instance for each call.

According to the javadoc, Integer.valueOf(123) has the difference it caches Objects... so you may (or may not) end up with the same Object if you call it more than once.

For instance, the following code:

   public static void main(String[] args) {

        Integer a = new Integer(1);
        Integer b = new Integer(1);

        System.out.println("a==b? " + (a==b));

        Integer c = Integer.valueOf(1);
        Integer d = Integer.valueOf(1);

        System.out.println("c==d? " + (c==d));

    }

Has the following output:

a==b? false
c==d? true

As to using the int value, you are using the primitive type (considering your method also uses the primitive type on its signature) - it will use slightly less memory and might be faster, but you won't be ale to add it to collections, for instance.

Also take a look at Java's AutoBoxing if your method's signature uses Integer- when using it, the JVM will automatically call Integer.valueOf() for you (therefore using the cache aswell).