Boxing (computer programming): Difference between revisions

Content deleted Content added
Line 23:
For example, in versions of Java prior to J2SE 5.0, the following code did not compile:
 
<source lang="java">
Integer i = new Integer(9);
Integer j = new Integer(13);
Integer k = i + j; // error!
</source>
 
As of J2SE 5.0, the <code>Integer</code>s <code>i</code> and <code>j</code> are unboxed into <code>int</code>s, the two are added, and then the sum is autoboxed into a new <code>Integer</code>. [http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html] Originally, the compiler would not accept the last line. <code>Integer</code>s are objects, on the surface no different from <code>List</code>, <code>Object</code>, and so forth; mathematical operators such as <code>+</code> were not meaningfully defined for them. But the following code would of course be accepted without complaint:
 
<source lang="java">
int i = 9;
int j = 13;
int k = i + j;
</source>
 
Another example:
 
<source lang="java">
int x = 4;
int y = 5;
// Integer qBox = new Integer(x + y);
Integer qBox = x + y; // would have been an error, but okay now - equivalent to previous line
</source>
 
[[Category:Data types]]