Boxing (computer programming): Difference between revisions

Content deleted Content added
m Boxing: - Capitalization, removed contractions, <code> around int
Line 4:
 
==Boxing==
'''boxingBoxing''' is to place a primitive type within an object so that the primitive can be used as an object, in a language where there is a distinction between a primitive type and an object type. For example, [[list|lists]] may have certain [[methods]] which [[arrays]] might not, but the list might also require that all of its members be objects. In this case, the added functionality of the list might be unavailable to a simple list of numbers.
 
For a more concrete example, in Java, a LinkedList can change its size, but an array must have a fixed size. You might desire to have a LinkedList of ints<code>int</code>s, but the LinkedList class only lists objects -- it cannot list primitive types.
 
To get around this, you can box your ints<code>int</code>s into Integers, which are objects, and then you can create a LinkedList of Integers.
 
===Autoboxing===
Autoboxing is the term for treating a primitive type as an object type without any extra code.
 
For example, as of Java 5.0, Java will now allow you to create a LinkedList of ints<code>int</code>s. This doesn'tdoes not contradict what was said above: The LinkedList still only lists objects, and it cannot list primitive types. But now, when Java expects an object but receives a primitive type, it immediately converts that primitive type to an object.
 
This action is called autoboxing, because it is boxing that is done automatically (and implicitly) by the computer, instead of requiring you to do it yourself.
Line 20:
Unboxing is the term for treating an object type as a primitive type without any extra code.
 
For example, in versions of Java prior to 5.0, the following code didn'tdid not compile:
 
Integer i = new Integer(9);
Line 26:
Integer k = i + j;
 
The last step, in particular, doesn'tdoes not make much sense. Integers are objects; they're are nebulous blocks of code somewhere else. What does it mean to add them? But the following code is perfectly okay:
 
int i = 9;
Line 32:
int k = i + j;
 
As of Java 5.0, the first example is now treated just like the second example. The Integer is '''unboxed''' into an <code>int</code>, the two are added, and then the sum is '''autoboxed''' into a new Integer.
 
[[Category:Data types]]