Autoboxing and Unboxing
We have already worked with different types of objects of Wrapper classes. But, it still requires lot of coding effort to put in. That is why are looking for better alternative which reduces the amount of coding while working with Wrapper classes. In this regard, Java provides us two options: Autoboxing and Unboxing.
Autoboxing is a language feature that reduces the programmer’s coding effort when it comes to working with the primitive wrapper types. Consider this code fragment:
int num = 25; int numObject = new Integer(num);
Primitive wrapper objects, such as the Integer class used here, were Java’s way of allowing us to treat primitive types as though they were objects. Consequently, we were expected to ‘wrap’ our primitive type with the corresponding primitive wrapper object, as shown above. But Java (since JSE 5) allows us to do the following:
int num = 25;
Integer newObject = num; // autoboxing
In the last statement, the variable num has been ‘automatically boxed up’ on our behalf. Basically, this implicitly calls “new Integer(num)” here.
Unboxing on the other hand uses the same process in reverse. Study the following code snippet for a moment:
int i = numObject.intValue();
The above code statement converts the wrapper object to its primitive type using intValue() method. The same operation can be replaced by unboxing as follows:
int j = newObject; // unboxing
Basically, Java will automatically ‘unbox’ this for us by implicitly calling the intValue() method on the wrapper type object.
See the complete program below.
BoxingDemo.java
public class BoxingDemo {
public static void main(String[] args) {
int num = 25;
Integer numObject, newObject;
//without autoboxing
numObject = new Integer(num);
System.out.println("numObject: " + numObject);
//using autoboxing
newObject = num;
System.out.println("newObject: " + newObject);
//without unboxing
int i = numObject.intValue();
System.out.println("i: " + i);
//using unboxing
int j = newObject;
System.out.println("j: " + j);
}
}
Output:
numObject: 25
newObject: 25
i: 25
j: 25
NOTE: Keep in mind that the Java compiler still creates the wrapper code implicitly, so we don’t really gain anything here in terms of performance. Consider this feature as a programmer convenience, not a performance booster.