Autoboxing and Unboxing in Java

As we know that primitive data types cannot participate in object-like activities, and java provides solution to this in form of wrapper classes. Each primitive type has a corresponding wrapper class that stores the values of that type, and they can act as objects. So, you wrap a primitive value into the corresponding wrapper object and then that value can act as an object type. This process is called boxing. When you need the primitive value back, you retrieve it from the wrapper by invoking an appropriate method on it. This is called unboxing

If there is a lot of boxing and unboxing going on, your program becomes cluttered and you are doing the same thing over and over again: boxing and unboxing. J2SE 5.0 presents a solution to this problem by automating boxing and unboxing, a feature known as autoboxing.

Autoboxing is the capability to assign a primitive value to a corresponding wrapper type; the conversion from primitive type to wrapper type is automated. Auto-unboxing is the reverse of autoboxing: that is, the capability to assign a wrapper type to the corresponding primitive type; the conversion from wrapper to primitive is automated. 

Autoboxing is also sometimes used, for short, to refer to both autoboxing and auto-unboxing.



Without autoboxing, you will need to do wrapping and un-wrapping manually. As an example, consider the following code fragment:


            public Double areaOfSquare(Double side) {
       double d = side.doubleValue();
       double a = d * d;
       return new Double(a);
     }


In this code fragment, you unwrap the double value, calculate area, and then wrap the result again before returning it. You had to do this boxing and unboxing manually before J2SE 5. But now in J2SE 5, you can simply replace the preceding code fragment with the following:
  

    public Double areaOfSquare(Double side){

       return side*side;

    }

Remember that, the boxing and unboxing is still done, but it’s done automatically; it’s hidden from you. Therefore, although it may seem as if you can treat wrappers just like primitives, you can make mistakes if you forget the fact that boxing and unboxing is still being done transparently.

Also remember that Autoboxing and unboxing will work only between corresponding primitives and wrappers, such as int and Integer, double and Double, and float and Float. If you cannot box a primitive type into a wrapper, you cannot autobox it either. 

 

No comments:

Post a Comment