Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);

Harry Quince picture Harry Quince · Apr 20, 2009 · Viewed 15.2k times · Source

Autoboxing seems to come down to the fact that I can write:

Integer i = 0; 

instead of:

Integer i = new Integer(0);

So, the compiler can automatically convert a primitive to an Object.

Is that the idea? Why is this important?

Answer

Brian Gianforcaro picture Brian Gianforcaro · Apr 20, 2009

You kind of simplified it a little too much.

Autoboxing also comes into play when using collections. As explained in sun's java docs:

Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class. ... 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.

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Great overview of Autoboxing