What is autoboxing?

Questions by krishna_darl   answers by krishna_darl

Showing Answers 1 - 3 of 3 Answers

zhufeng87

  • May 23rd, 2006
 

As any Java programmer knows, you can?t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). 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.

  Was this answer useful?  Yes

elimesika

  • Aug 8th, 2006
 

Autoboxing and Auto-Unboxing of Primitive Types

Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like Integer and Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only needed for a method call to the Collections API, for example.

The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow. In the next example an int is being stored and then retrieved from an ArrayList. The 5.0 version leaves the conversion required to transition to an Integer and back to the compiler.

Before

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();

After

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions