Oleg Mikheev
Oleg Mikheev

Reputation: 17444

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?

Upvotes: 3

Views: 4255

Answers (2)

Jesper
Jesper

Reputation: 206796

Yes. The compiler automatically translates this:

Boolean b1 = true;

into this:

Boolean b1 = Boolean.valueOf(true);

which always returns one of the two constants Boolean.TRUE or Boolean.FALSE.

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

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);
}

Upvotes: 10

Related Questions