Autoboxing and unboxing in Java are features that allow primitive data types to be automatically converted to their corresponding wrapper classes and vice versa.
Autoboxing
Process of automatically converting a primitive data type to its corresponding wrapper class called as Autoboxing in Java. This feature was introduced in Java 5 to simplify the process of working with primitive data types in situations where wrapper classes are required. Here is an example of autoboxing in Java:
// Autoboxing example
int num = 10; // primitive int value
Integer numObj = num; // autoboxing - converting int to Integer
System.out.println("Primitive int value: " + num);
System.out.println("Autoboxed Integer value: " + numObj);
In the example above, we have a primitive int variable num
with a value of 10. We then assign the value of num
to an Integer object numObj
. This assignment triggers autoboxing, where the primitive int value is automatically converted to an Integer object.
When we print the values of num
and numObj
, you will see that the primitive int value and the autoboxed Integer value are displayed. Autoboxing simplifies the process of converting primitive data types to their corresponding wrapper classes, making code cleaner and easier to work with in situations where wrapper classes are required.
Unboxing
Unboxing in Java is the process of automatically converting a wrapper class object to its corresponding primitive data type. This feature, introduced in Java 5 along with autoboxing, simplifies the process of working with wrapper classes in situations where primitive data types are required. Here is an example of unboxing in Java:
// Unboxing example
Integer numObj = 20; // Integer object
int num = numObj; // unboxing - converting Integer to int
System.out.println("Integer object value: " + numObj);
System.out.println("Unboxed int value: " + num);
In the example above, we have an Integer object numObj
with a value of 20. We then assign the value of numObj
to a primitive int variable num
. This assignment triggers unboxing, where the Integer object is automatically converted to an int value.
When we print the values of numObj
and num
, you will see that the Integer object value and the unboxed int value are displayed. Unboxing simplifies the process of converting wrapper class objects to their corresponding primitive data types, making code cleaner and easier to work with in situations where primitive data types are required.
Conclusion on Autoboxing and Unboxing
Autoboxing and unboxing are convenient features that help simplify code and make it more readable. However, they can also have performance implications, as they involve extra overhead in terms of memory and CPU usage. It is important to consider these implications when using autoboxing and unboxing in performance-critical applications.
Sample program is available on git