Since JDK 5.0, auto boxing/unboxing was introduced in Java. The trick is simple and helpful, but when I started testing different conversions between wrapper classes and primitive types, I get really confused how the concept of auto boxing works in Java. For example:
Boxing
int intValue = 0;
Integer intObject = intValue;
byte byteValue = 0;
intObject = byteValue; // ==> Error
After trying different cases (short
, long
, float
, double
), the only case which is accepted by the compiler is when the type of the value on the right of affectation operator is int
.
When I looked inside the source of Integer.class
I found that it implements only one constructor with int
parameter.
So my conclusion is that the concept of auto boxing is based on constructor implemented in the wrapper class. I want to know if this conclusion is true or there is another concept used by auto boxing?
Unboxing
Integer intObject = new Integer(0);
byte byteValue = intObject; // ==> Error (the same Error with short)
int intValue = intObject;
double doubleValue = intObject;
My conclusion about unboxing is that the wrapper class gives the value wrapped by the object in the corresponding type (Integer
==> int
), then the compiler use the usual rules of converting primitive types (byte
=> short
=> int
=> long
=> float
=> double
).
I want to know if this conclusion is true or there is another concept used by auto unboxing?
byte byteValue = intObject;
- you do realize that's an error regardless of whetherintObject
is an object or a primitive type, right? – SkylarInteger.intValue()
to unbox the wrapped value, is this correct? – Aguascalientes