Quick question: is it guaranteed that this code always prints true
?
Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1 == b2);
Boxing of boolean seems to result in the same Boolean object all the time, but I couldn't find too much info about boxed Boolean equality in JLS. On contrary, it even seems to suggest that boxing is supposed to create new objects and may even result in OOM exceptions.
What are your thoughts?
From the Java Language Specification on Boxing Conversion
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:
- From type
boolean
to typeBoolean
[...]
If the value
p
being boxed is an integer literal of typeint
between-128
and127
inclusive (§3.10.1), or theboolean
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
.
This is relatively simply implemented as
/**
* The {@code Boolean} object corresponding to the primitive
* value {@code true}.
*/
public static final Boolean TRUE = new Boolean(true);
/**
* The {@code Boolean} object corresponding to the primitive
* value {@code false}.
*/
public static final Boolean FALSE = new Boolean(false);
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}