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?
valueOf() returns an Integer object while Integer. parseInt() returns a primitive int. Both String and integer can be passed a parameter to Integer.
valueOf(String str) is an inbuilt method which is used to return an Integer object, holding the value of the specified String str. Parameters: This method accepts a single parameter str of String type that is to be parsed.
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.
The valueOf() method is a static method which returns the relevant Integer Object holding the value of the argument passed. The argument can be a primitive data type, String, etc.
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
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With