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

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).

Leave a Comment