Monday, February 2, 2009

Autoboxing in Java 5

Hi,
In this post, I am going to discuss about Autoboxing but before that let me explain Wrapper classes. The main purpose of wrapper classes:
Java programmers often need some mechanism to wrap primitive values in an object so that the primitives can be used in activities reserved for objects, like adding into and retreiving from the collections, returning object from a method etc. Wrapper classes serves this.
With the help of autoboxing and unboxing (features provided by Java 5), most of the wrapping features, that user needs to do manually are now handled automatically.

Using Java 4, you may want to use wrapper classes as follows:

Integer x = new Integer(100); // make it
int y = x.intValue(); // unwrap it
y++; // increment the value
x = new Integer(y); // re-wrap it
System.out.println(y); // print it

Using Java 5 (Autoboxing feature), you may want to use wrapper classes as follows:

Integer y = new Integer(100);
y++;
System.out.println(y);
Both examples produce the output:

101

3 comments: