Autoboxing And Unboxing
1. Short answer
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class (e.g., int
→ Integer
).
Unboxing is the automatic conversion of a wrapper class to its corresponding primitive type (e.g., Integer
→ int
). Java handles these conversions behind the scenes, making it easier to work with both primitives and wrapper objects.
2. Long answer
Autoboxing and unboxing are Java features that automatically convert between primitive types and their corresponding wrapper classes.
Autoboxing
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class. Java does this behind the scenes when you assign a primitive to a wrapper object or add a primitive to a collection that requires objects.
For example:
int num = 10;
Integer wrapperNum = num; // Autoboxing: int -> Integer
In this case, the primitive int
is automatically converted to the wrapper Integer
.
Unboxing
Unboxing is the reverse process, where a wrapper class is automatically converted back to its corresponding primitive type. This happens when you perform operations that expect a primitive type.
For example:
Integer wrapperNum = 10;
int num = wrapperNum; // Unboxing: Integer -> int
Here, the Integer
object is automatically converted to the primitive int
.
Summary
- Autoboxing: Primitive → Wrapper (e.g.,
int
→Integer
) - Unboxing: Wrapper → Primitive (e.g.,
Integer
→int
)
Java handles these conversions automatically, making it easier to work with primitives and their wrappers seamlessly.