Autoboxing and Unboxing

image

Autoboxing is a feature that came into Java with the JDK 1.5 release. It recognizes the very close relationship between primitive variables and objects of their corresponding wrapper type, and provides a little extra help from the compiler. Autoboxing says that you can convert from one to the other without explicitly writing the code. The compiler will provide it for you.

In releases before 1.5, you could get an int value into a java.lang.Integer like this:

int i = 27;
Integer myInt = new Integer(i);

With autoboxing, you can make the assignment directly, and the compiler looks at the types of the variables, and says “yes, I know how to wrap (or “put a box around”) an int to get an Integer object”. Then it allows the expression, and generates the code to do it. So you may write this instead:

int i = 27;
Integer myInt = i;          //  autobox!

Unboxing is the same concept going the other way, from a primitive-wrapper object to a primitive type. Here's an example with a wrapper object for the Double type:

Double dObj = 27.0;  // autobox
double d = dObj;     // unbox, gets value 27.0

Boxing isn't just for variable creation or initialization. You can use it wherever the context expects a primitive and you have the corresponding wrapper. It gets automatically wrapped for you. Here's an example showing how we can use a Boolean object where a boolean primitive is expected:

Boolean isReady = new Boolean(false);

if (isReady)  { /* more code */

Here's an example where unboxing is done in an expression:

Float fObj1 = 20.0F;  // boxing
Float fObj2 = 10.0F;  // boxing
float result = fObj1 * fObj2;  // unboxing
Float fObj3 = fObj1 * 23.0F;   // boxing and unboxing

When you compile programs with new JDK 1.5 features, you'll need to add two options on the command line, like this:

javac  -source 1.5  -target 1.5  myfile.java

(This was true at the time we went to press, but Sun may make last minute changes to the compiler options. The latest information will be on the website afu.com/jj6.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.10