In Java
Integer i=10;
Integer
as wrapper class. How it is initialised while it's an object reference only? Could anybody explain that?
In Java
Integer i=10;
Integer
as wrapper class. How it is initialised while it's an object reference only? Could anybody explain that?
The statement
Integer i = 10;
is short for:
Integer i; // Variable declaration
i = 10; // Variable assignment
So first of all Java creates a variable called i
which is allowed to refer to instances of type Integer
.
After that the right side is executed, 10
is an integer literal of type int
(see JLS§3.10.1). Then Java tries to assign the int
to your Integer
variable i
. The types differ, for a regular case the assignment would not be possible.
However, Java is able to automatically convert int
to Integer
and vice versa. This is called autoboxing, Java can do this for all primitives and their wrapper (see JLS§5.1.7).
So Java converts your int
10
to the wrapper type Integer
by using Integer.valueOf(10)
. In fact, since the number is small (-128
to +127
) the method returns a cached Integer
out of an internal pool instead of creating a new instance.
So after Java magic your code is:
Integer i = Integer.valueOf(10);
which is a valid assignment as the right side is also an Integer
and not an int
anymore.
Actually the usage of Integer.valueOf
is not described in the JLS. It only says that Java must be able to automatically convert int
to Integer
(from JLS§5.1.7):
If
p
is a value of typeint
, then boxing conversion convertsp
into a referencer
of class and typeInteger
, such thatr.intValue() == p
.
But most JVM implementations use that method (you can see that in the resulting byte code).