When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:
If you look up the API doc for Integer#valueOf(int), you'll see it was added in JDK 1.5. All the wrapper types (that didn't already have them) had similar methods added to support autoboxing. For certain types there is an additional requirement, as described in the JLS:
If the value p being boxed is
true
,false
, abyte
, achar
in the range\u0000
to\u007f
, or anint
orshort
number between-128
and127
, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2. §5.1.7
It's interesting to note that long
s aren't subject to the same requirement, although Long values in the -128..127
range are cached in Sun's implementation, just like the other integral types.
I also just discovered that in my copy of The Java Programming Language, it says char
values from \u0000
to \u00ff
are cached, but of course the upper limit per the spec is \u007f
(and the Sun JDK conforms to the spec in this case).