Convert primitive to wrapper class & vice-versa

Q. Write a program to convert primitive to wrapper class and wrapper to primitive.

Answer:

Autoboxing:
The process of converting a primitive data type into corresponding wrapper class object is known as autoboxing. E.g. int to Integer.

Unboxing:
Converting an object of wrapper class into corresponding primitive data type is known as unboxing. E.g. Integer to int.

In this example, we perform autoboxing and unboxing to convert the primitive type to object type and vice-versa.

WrapperDemo.java

class WrapperDemo
{
        public static void main(String[] args)
        {
                //Autoboxing
                System.out.println("Example of Autoboxing");
                int a = 50;
                Integer b = Integer.valueOf(a);
                Integer c = a + b;
                System.out.println("a: "+a+" b: "+b+" c: "+c);
                System.out.println("==================");

                //Unboxing
                System.out.println("Example of Unboxing");
                Integer x = new Integer(15);
                int y = x.intValue();
                int z = x * y;
                System.out.println("x: "+x+" y: "+y+" z: "+z);
        }
}


Output:

primitive to wrapper