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
.