I\'m trying to determine whether the following statements are guaranteed to be true:
((Boolean)true) == Boolean.TRUE
((Boolean)true) == Boolean.valueOf(true)
Autoboxing is absolutely implemented using valueOf()
...in the OpenJDK. If that's your implementation, read on... if not, skip to below.
((Boolean)true) == Boolean.TRUE
((Boolean)true) == Boolean.valueOf(true)
Java documentation states that Boolean.valueOf()
always returns Boolean.TRUE
or Boolean.FALSE
, therefore your reference comparisons in these cases will succeed.
((Integer)1) == Integer.valueOf(1)
For this particular example, under the OpenJDK implementation with default settings, it will probably work by virtue of the fact that you picked a value < 128 which is cached at startup (although this can be overridden as a commandline arg). It may also work for larger values if it's frequently used enough to be cached. Unless you're working under "safe" assumptions about the Integer cache, don't expect the reference comparison to be an equality.
Long
, Short
, Character
and Byte
incidentally implement this caching too, but unlike Integer
, it's not tunable. Byte
will always work if you're comparing autobox/valueOf()
references since obviously, you can't go out of range. Float
and Double
will unsurprisingly always create a new instance.
Now, in purely generic terms? See this section of the JLS - you MUST be given equal references for boolean
and any int
or char
within the -128 to 127 range. There are no guarantees for anything else.