AutoBoxing and UnBoxing in Java

Autoboxing and unboxing is a mechanism provided by Java to automatically convert primitive Data Type into its corresponding Wrapper Class Object and vice versa.

Consider the Code below of the problem without Autoboxing and unBoxing.

public class AutoBox {

    public static void main(String[] arg) {
        int myIntValue = 10;
        Integer myIntegerValue = new Integer(10);

        // Assigning int to Wrapper
        myIntegerValue = Integer.valueOf(myIntValue);

        // Assigning Integer to primitive value int
        myIntValue = myIntegerValue.intValue();

    }

}

In the above code we have created one primitive type int value and one value of Wrapper Class Integer. If there is no concept of autoboxing then to assign an int value to Integer class Integer.valueOf(int i) method needs to used, and similarly for unboxing Integer.intValue() method needs to be used. But fortunately Java provides auto type conversion between primitive data type and its corresponding wrapper Class.

public class AutoBox {

    public static void main(String[] arg) {
        int myIntValue = 10;

        // Unboxing (Assigning primitive value to Wrapper Class.
        Integer myIntegerValue = 10;

        // Assigning int to Wrapper (Autoboxing)
        myIntegerValue = myIntValue;

    }

}

 

Livewire Component Library
Primitive Type Wrapper Class
boolean Boolean
byte Byte
char Character
float Float
int Integer
short Short
double Double

Site Footer