Tuesday, October 19, 2010

Autoboxing in java


Autoboxing, introduced in Java 5, is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, double and Double, etc). The underlying code that is generated is the same, but autoboxing provides a sugar coating that avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types.

In the previous section on wrapper classess for primitive type values, we discussed how to create an instance of a wrapper from a primitive and conversely, how to obtain the primitive value held by the wrapper. This involves a a certain amount of clumsy code.
For example, creating a Float object from a float primitive is straightforward:
  float primitive_float = 3.0f;
  Float wrapper_float = new Float (primitive_float);
Going the other direction, however, requires explicitly calling the floatValue() method on the Float object:
  float primitive_float = wrapper_float.floatValue ();
If you are dealing with a lot of instances of wrappers and conversions, you will thus need to deal with a lot of method invocations.
In J2SE 5.0, however, the code to create the wrapper object allows for this much simpler form:
  Float wrapper_float = primitive_float;
Here, the "wrapping" is done automatically! There is no need to explicitly call the Float constructor. This "wrapping" is called "autoboxing" in the sense that the primitive value is automatically "boxed up" into the wrapper object. Autoboxing is available for all the primitive/wrapper types.
Going the other way, from object type to primitive, is just as simple:
  Integer wrapper_integer = 5; // primitive 5 autoboxed into an Integer
  int primitive_int = wrapper_integer; // automatic unboxing Integer into int


Now we can have this.
int i;
Integer j;
i = 1;
j = 2;
i = j;
j = i;
Earlier we had to do this.
int i;
Integer j;
i = 1;
j = new Integer(2);
i = j.intValue();
j = new Integer(i);
This is quite clumsy.

Also see - Some issues with Autoboxing

No comments:

Post a Comment

Chitika