New Integer vs valueOf

I was using Sonar to make my code cleaner, and it pointed out that I'm using new Integer(1) instead of Integer.valueOf(1). Because it seems that valueOf does not instantiate a new object so is more memory-friendly. How can valueOf not instantiate a new object? How does it work? Is this true for all integers?


Solution 1:

Integer.valueOf implements a cache for the values -128 to +127. See the last paragraph of the Java Language Specification, section 5.1.7, which explains the requirements for boxing (usually implemented in terms of the .valueOf methods).

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

Solution 2:

From the JavaDoc:

public static Integer valueOf(int i) Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

ValueOf is generaly used for autoboxing and therefore (when used for autoboxing) caches at least values from -128 to 127 to follow the autoboxing specification.

Here is the valueOf implementation for Sun JVM 1.5.? Have a look at the whole class to see how the cache is initialized.

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}

Solution 3:

they are pushing you to use valueOf() instead of new Integer() so the method valueOf() does it for you, and caches the value in case you want to get the same number again in future. In that case, method won't instatiate new Integer, but will give you the cached one, what will make 'creation' of new Integer a lot quicker and memory friendly process..

This way you may cause yourself alot of problems if you are unexperienced java programmer since you will conclude that Integer.valueOf(342)==Integer.valueOf(342), because you may (or may not) have the same pointer for two Integers, and probably you will practise it in a way, let's say, you learned in C#, so that will show you bugs from time to time, and you won't know how & where those came from...