Tuesday, October 1, 2013

What is autoboxing and unboxing?

Autoboxing is the automatic conversion of Primitive Data Types into their respective Wrapper classes. The primitive type is boxed into a wrapper class. Unboxing is the reverse conversion where the primitive type is unboxed from the Wrapper Class. This conversion is done by Java compiler. This feature was introduced in Java 5.

Autoboxing Example:
int number1 = 10;
Integer number2 = number1;

The variable number1 of primitive type is autoboxed into a Wrapper class of type Integer for the assignment.

Unboxing Example:
Integer number3 = 5;
int number4 = number3;

The variable number3 of Integer Wrapper class type is unboxed into a primitive type for the assignment.

No comments:

Post a Comment