Pages

Tuesday, 17 April 2012

Autoboxing and Unboxing in Java

Excerpts from the reference :

Definition : You can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.

Advantages : The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats.Use them only when you have to put code in collections.

Disadvantages :
1)  An Integer expression can have a null value.
2) If your program tries to autounbox null, it will throw a NullPointerException.
3) The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions.
4) There are performance costs associated with boxing and unboxing, even if it is done automatically.

Example :
You can write Integer i = 5; instead of Integer i = Integer.valueOf(5); or Integer i = new Integer(5);  

Reference :
1) http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

Tip : This feature was introduced in JDK 5.

 Java supplies built-in reference types known as wrapper types, one for each of the primitive types:
Java automatically converts from primitive types to wrapper types (autoboxing) and back (auto-unboxing) when warranted

No comments:

Post a Comment