I'm trying to determine whether the following statements are guaranteed to be true:
((Boolean)true) == Boolean.TRUE
((Boolean)true) == Boolean.valueOf(true)
((Integer)1) == Integer.valueOf(1)
I've always assumed that autoboxing was equivalent to calling valueOf()
on the corresponding type. Every discussion that I've seen on the topic seems to support my assumption. But all I could find in the JLS was the following (§5.1.7):
If the value
p
being boxed is an integer literal of typeint
between-128
and127
inclusive (§3.10.1), or the boolean literaltrue
orfalse
(§3.10.3), or a character literal between'\u0000'
and'\u007f'
inclusive (§3.10.4), then leta
andb
be the results of any two boxing conversions ofp
. It is always the case thata == b
.
That describes behavior identical similar* to that of valueOf()
. But there doesn't seem to be any guarantee that valueOf()
is actually invoked, meaning there could theoretically be an implementation that keeps a separate, dedicated cache for autoboxed values. In such a case, there might not be identity equality between cached autoboxed values and regular cached boxed values.
Oracle's autoboxing tutorial states matter-of-factly that li.add(i)
is compiled to li.add(Integer.valueOf(i))
, where i
is an int
. But I don't know whether the tutorial should be considered an authoritative source.
*It's a slightly weaker guarantee than valueOf()
, as it only refers to literal values.
valueOf()
; my question is whether the JLS makes any guarantee in that regard. – RabelaisvalueOf
and none of the hits were related to autoboxing (only stuff aboutEnum.valueOf
etc). In my opinion that settles it. – GausevalueOf
, or if javac switched to another solution, then any new bytecode emitted would be incompatible with old bytecode, since the old bytecode usedvalueOf
for the autoboxing, and two autoboxed values must (at least under some circumstances) be referentially equivalent. Now to tie this up to a formal proof one would have to find something in JLS stating certain guarantees for split compilations. I doubt JLS covers such topics though. – GauseInteger.valueOf
then old autoboxing code wouldn't be compatible with new autoboxing code. (Or rather, the new compiler wouldn't be compatible with the old compiler, despite both adhering to JLS, which seems a bit contradictory.) – GausevalueOf
is the most appropriate method for autoboxing and that there is no reason (at least obviously) to do otherwise. – DricvalueOf
is the appropriate and best solution, but that's not what this question is about. – GausevalueOf()
, since there would be no behavioral difference. – RabelaisvalueOf
is required. – GausevalueOf
? IfvalueOf
continues to do the right thing, I see no reason not to call it in a compiled class. Anything more fancy could be injected by the JVM, replacing the call, at runtime. Just like it may already happen today. – Stipel