Junior
How to convert reference types to primitive types and vice versa?
sobes.tech AI
Answer from AI
Conversion of reference types (wrappers) to primitive types (unboxing) and vice versa (autoboxing) occurs automatically in Java, but it can also be done explicitly.
Autoboxing: Automatic conversion of a primitive type to its corresponding reference type.
int primitiveInt = 10;
// Automatically converted to Integer
Integer wrapperInt = primitiveInt;
Unboxing: Automatic conversion of a reference type to its corresponding primitive type.
Integer wrapperInteger = 20;
// Automatically converted to int
int primitiveInteger = wrapperInteger;
Explicit conversion:
Converting a reference type to a primitive: using methods like intValue(), doubleValue(), etc.
Integer wrapperInt = 30;
int primitiveInt = wrapperInt.intValue(); // explicit conversion
Double wrapperDouble = 40.5;
double primitiveDouble = wrapperDouble.doubleValue(); // explicit conversion
Converting a primitive type to a reference type: using wrapper class constructors or static methods valueOf(). The static method valueOf() is preferred as it can cache values.
int primitiveInt = 50;
Integer wrapperInt = new Integer(primitiveInt); // constructor (deprecated)
double primitiveDouble = 60.7;
Double wrapperDouble = Double.valueOf(primitiveDouble); // using valueOf()
Conversion table:
| Primitive Type | Reference Type |
|---|---|
| boolean | Boolean |
| byte | Byte |
| short | Short |
| char | Character |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |