How would you translate reference types to primitive types and vice versa?
sobes.tech AI
Answer from AI
For reference types (e.g., Integer, Double, Boolean), unboxing is used to convert to primitive types (int, double, boolean). The JVM automatically converts the reference type to its primitive equivalent when necessary.
// Primitive type
int primitiveInt = 10;
// Creating a reference type from a primitive (auto-boxing)
Integer objectInt = primitiveInt; // Automatic conversion of int to Integer
// Converting a reference type back to a primitive (auto-unboxing)
int newPrimitiveInt = objectInt; // Automatic conversion of Integer to int
For primitive types to reference types (e.g., int to Integer, double to Double, boolean to Boolean), auto-boxing is used. The JVM automatically creates an object of the reference type from the primitive value.
// Primitive type
double primitiveDouble = 3.14;
// Creating a reference type from a primitive (auto-boxing)
Double objectDouble = primitiveDouble; // Automatic conversion of double to Double
// Converting a reference type back to a primitive (auto-unboxing)
double newPrimitiveDouble = objectDouble; // Automatic conversion of Double to double
It is important to remember that unboxing a reference type to a primitive can throw a NullPointerException if the reference type is null.
Also, before auto-boxing/unboxing was introduced, explicit methods of wrapper classes such as intValue(), doubleValue(), booleanValue() were used to convert reference types to primitives, and constructors or static methods like valueOf() were used to convert primitives to reference types. Auto-boxing/unboxing has greatly simplified this process.
// Explicit conversion before auto-boxing/unboxing
Integer explicitInteger = new Integer(25); // Constructor (deprecated)
int explicitInt = explicitInteger.intValue(); // Using intValue() method
// Using the static method valueOf() (preferred)
Integer valueOfInteger = Integer.valueOf(50);
int valueOfInt = valueOfInteger.intValue();