Autoboxing and Unboxing in Java
Autoboxing and Unboxing are the features included in Java 1.5 , where the auto conversion happens from Primitive Type to its corresponding Wrapper Class type and Vice-Versa.
Autoboxing is the process of converting a primitive type data into its corresponding wrapper class object instance. It involves the dynamic allocation of memory and initialization of an object for each primitive. In autoboxing there is no need to explicitly construct an object.
Unboxing is the process of converting a wrapper instance into a primitive type . It is a process through which the value of a boxed object type is automatically unboxed from wrapper when its value is required. In order to do this, there is no need to call a method such as doubleValue() or intValue().
When it required ?
When a method is expecting a wrapper class object but the value that is passed as parameter is a primitive type. When primitive value assigned to wrapper class variable or reverse.
No need to make object explicitly and wrap the value of primitive type.
“Autoboxing” is too unexpected in its behavior and can easily result in difficult to recognize errors.
Autoboxing does create objects which is not clearly visible in the code. So when autoboxing occurs performance suffers.
What is a Wrapper Class ?
A wrapper class is a class that “wraps” the functionality of another class or component. That is, it wraps around a primitive data type and gives it an object appearance. The advantage is that it can be used whenever the primitive data type is required as an object. Wrapper class provide a wide range of function to be performed on the primitive types.