Search code examples
javaprimitiveautoboxing

Equality of boxed boolean


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?


Solution

  • 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 type Boolean

    [...]

    If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == 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);
    }