Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 237
MicNeo Avatar asked Jan 27 '12 08:01

MicNeo


People also ask

What does new integer do?

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.

Why use integer valueOf?

valueOf(int a) is an inbuilt method which is used to return an Integer instance representing the specified int value a. Parameters : The method accepts a single parameter a of integer type representing the parameter whose Integer instance is to be returned.

How do you create a new integer in Java?

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

What is integer [] in Java?

A int is a data type that stores 32 bit signed two's compliment integer. On other hand Integer is a wrapper class which wraps a primitive type int into an object. 2. Purpose. int helps in storing integer value into memory.


3 Answers

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

like image 108
Marcelo Avatar answered Oct 11 '22 14:10

Marcelo


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.

Parameters:
i - an int value.
Returns:
a Integer instance representing i.
Since:
1.5

refer http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#valueOf%28int%29

This variant of valueOf was added in JDK 5 to Byte, Short, Integer, and Long (it already existed in the trivial case in Boolean since JDK 1.4). All of these are, of course, immutable objects in Java. Used to be that if you needed an Integer object from an int, you’d construct a new Integer. But in JDK 5+, you should really use valueOf because Integer now caches Integer objects between -128 and 127 and can hand you back the same exact Integer(0) object every time instead of wasting an object construction on a brand new identical Integer object.

private static class IntegerCache {
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
    for(int i = 0; i < cache.length; i++)
    cache[i] = new Integer(i - 128);
}
}

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);
}

refer Why YOU should use Integer.valueOf(int)

EDIT

autoboxing and object creation:

The important point we must consider is that autoboxing doesn't reduce object creation, but it reduces code complexity. A good rule of thumb is to use primitive types where there is no need for objects, for two reasons:

Primitive types will not be slower than their corresponding wrapper types, and may be a lot faster. There can be some unexpected behavior involving == (compare references) and .equals() (compare values).

Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.

The following is the list of primitives stored as immutable objects:

  • boolean values true and false

  • All byte values

  • short values between -128 and 127

  • int values between -128 and 127

  • char in the range \u0000 to \u007F

refer http://today.java.net/pub/a/today/2005/03/24/autoboxing.html#performance_issue

like image 33
Hemant Metalia Avatar answered Oct 11 '22 14:10

Hemant Metalia


int is primitive type, not an object.

new Integer(123) and Integer.valueOf(123) both return Integer object representing value 123. As per javadoc for Integer.valueOf():

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.

like image 24
Jan Zyka Avatar answered Oct 11 '22 14:10

Jan Zyka