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.