Junior
How is the conversion of reference types to primitive types and vice versa carried out?
sobes.tech AI
Answer from AI
In Java (and Android), conversion between reference types (wrappers) and primitive types is called auto-boxing and auto-unboxing.
- Boxing — converting a primitive type to its corresponding wrapper object. For example,
inttoInteger. - Unboxing — converting a wrapper object back to a primitive.
Example:
int a = 5;
Integer boxed = a; // auto-boxing
int b = boxed; // auto-unboxing
Previously, you had to do this explicitly:
Integer boxed = Integer.valueOf(a);
int b = boxed.intValue();
Auto-boxing and auto-unboxing simplify working with collections and methods that require objects instead of primitives.