Unboxing in Java is the process of converting an object of a wrapper class back into its corresponding primitive type. This is done automatically by the Java compiler through a feature called autoboxing and unboxing, introduced in Java 5.
Example of Unboxing:
Here's a simple example demonstrating unboxing:
public class UnboxingExample {
public static void main(String[] args) {
// Creating a wrapper object
Integer num = 100; // Autoboxing: Integer object created from int
// Unboxing: Converting Integer object back to int
int intValue = num; // Automatic conversion from Integer to int
System.out.println("Integer value: " + num);
System.out.println("Unboxed int value: " + intValue);
}
}
Key Points:
- In the example,
numis anIntegerobject that holds the value100. - When assigning
numtointValue, Java automatically converts theIntegerobject to its primitiveinttype. - This process is seamless and does not require explicit casting.
Unboxing is particularly useful when working with collections (like ArrayList) that store objects, allowing you to retrieve primitive values easily.
