Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Integer vs valueOf

Tags:

java

sonarqube

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?

like image 688
LB40 Avatar asked Jun 04 '10 13:06

LB40


People also ask

What is the difference between integer parseInt and integer valueOf?

valueOf() returns an Integer object while Integer. parseInt() returns a primitive int. Both String and integer can be passed a parameter to Integer.

What is integer valueOf?

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.

What is new integer in Java?

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.

What is the argument type of integer valueOf ()?

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.


2 Answers

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

like image 60
Brett Kail Avatar answered Sep 24 '22 17:09

Brett Kail


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); } 
like image 40
pgras Avatar answered Sep 22 '22 17:09

pgras