Reputation: 151
I would like to know the difference between these two:
Integer I = 30; // is it autoboxing?
Integer I = new Integer(30); // I know it is autoboxing
Upvotes: 3
Views: 173
Reputation: 129517
There is a difference. The first will be treated as
Integer I = Integer.valueOf(30); // autoboxing
which will use an Integer
object already stored in an internal cache (this is true when autoboxing values in the range -127 to 128 inclusive). The second will explicitly create a new Integer
object.
You can see this for yourself:
Integer I1 = 30;
Integer I2 = 30;
System.out.println(I1 == I2);
true
vs
Integer I1 = new Integer(30);
Integer I2 = new Integer(30);
System.out.println(I1 == I2);
false
In general don't compare Integer
objects with ==
since that tests for reference equality. I was using it here to test if I1
and I2
refer to the same instance. In the first snippet, they do because the Integer
corresponding to the int
30
already exists in a cache, and this instance is used and assigned to both I1
and I2
. In the second snippet, they do not since we are creating two independent objects via new
.
By the way there is no autoboxing involved in the second case, you're just creating a simple new object. There is autoboxing in the first case because an int
is being implicitly converted to an Integer
.
You can actually see the effects of autoboxing by viewing the compiled bytecode with javap -c MyClass
.
Upvotes: 6
Reputation: 17595
In the first line you write
Integer I = 30;
At the first look you assign an integer (all number literals without an explicit type postfix are considered to be integers) to an object, you think the compiler should complain about incompatible types. But it does not, then this is where the magic happens -> auto boxing
! The compiler automatically boxes the integer 30
into the object I
, i.e. it creates an Object which hold the integer value 30
and assigns this to your reference.
In the line
Integer I = new Integer(30);
You explicitly use the new
to create an object. So you don't leave the compiler any chance to do anything. Actually, what made so sure that this is auto boxing
??
Besides of that, the jvm caches a range of values for constants to minimize the memory used for those constants an thus increase performance. To make use of this feature you should get instances of such object using the valueOf()
method. In that case for same integer value one unique object is returned. If you create it using new
then for the same constant you'll get a different object each time.
Upvotes: 2