Autoboxing and Unboxing in java

Autoboxing and Unboxing in java example


Autoboxing and Unboxing in java example


Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.
Autoboxing: When primitive data types convert automatically to convert to the wrapper class is know as Autoboxing. For example, byte converts to Byte, int to Integer, double to double, etc.
Auto-Unboxing: When the wrapper class converts automatically to the primitive data types is known as Autoboxing. For example Byte to byte, Integer to int, Long to long, Float to float, Double to double, etc.

This feature of java was added in java 5
public class AutBoxingUnBoxing
{
    public static void main(String args[])
    { 
        //Converting short (Primitive type) into Short (Wrapper class) 
        short a=45;  // assign value to short type
        //converting short into Short Explicitly
        Short b=Short. ValueOf (a);
        Short c=a; //autoboxing, no need to convert explicitly
        short d=c; // auto-unboxing
        System.out.println(a + " " + b + " " + b + " " + d);
    }
Output:
45 45 45 45
Here 45 assign as a short primitive type and convert it into Wrapper class by valueOf() method that is explicit. But Short c=a is automatically converted primitive to Wrapper (Autoboxing)

Advantages of autoboxing and unboxing


·         This feature of java lets developers write cleaner code
·         Automatically convert primitive to the wrapper and vice versa
·         Easier to comprehend and read.

AutoBoxing is very handy when developers are working with java.util.Collection. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type, we can create Collection only of Objects. For Example:

ArrayList<int> alist = new ArrayList<int>(); // not supported

ArrayList<Integer> alist = new ArrayList<Integer>(); // supported

Because ArrayList only works for an object. But by autoboxing, it is directly converted to object.
alist.add(20); //auto Boxing (automatically convert primitive to a collection type)


SHARE THIS
Previous Post
Next Post