Sunday, December 24, 2006

Java 5 Feature: An intro to Autoboxing

With Java 5 (or Java 1.5 or JSE 5.0 or Java J2SE 5.0 or JDK 1.5), a new feature called Autoboxing has been introduced to the language. it is the automatic conversion of the primitives and wrapper objects.
Boxing is to place a primitive data-type within an object so that the primitive can be used like an object. For example, a List, prior to JDK 1.5, can't store primitive data types. So, to store int type data in a List, a manual boxing was required (i.e from int to integer). Similarly, to retrieve the data back, an unboxing process was required to convert Integer back to int.

Autoboxing is the term for treating a primitive type as an object type. The compiler automatically supplies the extra code needed to perform the type conversion. For example, in JDK 1.5, it now allows the programmer to create an ArrayList of ints. This does not contradict what was said above for List: the ArrayList still only lists objects, and it cannot list primitive types. But now, when Java expects an object but receives a primitive type, it immediately converts that primitive type to an object.

This action is called Autoboxing, because it is boxing that is done automatically and implicitly instead of requiring the programmer to do so manually.

Unboxing is the term for treating an object type as a primitive type without any extra code.

For example, in versions of Java prior to 1.5, the following code did not compile:

Integer i = new Integer(9);
Integer j = new Integer(13);
Integer k = i + j; // error prior to JDK 1.5
Originally, the compiler would not accept the last line. As Integers are objects, mathematical operators such as + were not meaningfully defined for them. But the following code would of course be accepted without complaint:
int i = 9;
int j = 13;
int k = i + j;

int x = 4;
int y = 5;
// Integer qBox = new Integer(x + y);
Integer qBox = x + y;//would have been error,but okay now-equi to prev line
The Integer is unboxed into an int, the two are added, and then the sum is autoboxed into a new Integer.

Pros and Cons:
  • Autoboxing unclutters your code, but comes with important considerations in terms of performance and sometimes unexpected behavior.
  • Understand what == means. For objects, you are comparing identity, for primitive types, you are comparing value. In the case of auto-unboxing, the value based comparison happens.
  • If the Integer object is null, assigning in to int will result in a runtime exception – NullPointerException – being thrown.
Refer to Sun's Java Tutorial for more info.

1 comment:

Javin @ FIX Protocol Tutorial said...

Autoboxing is a great feature provided by JAVA5 but using it blindly may result in very subtle problem which will take hours and hours to
debug and find. to read more see the link
What is the problem while using '==' in autoboxing world in Java 5 ?



Popular Posts (Last 30 days)

This is a personal blog and I do not speak for my employer.