Comparing boolean and Boolean in Java
Someone recently asked me:
Java code:
if (someObject.isActive() == Boolean.FALSE)
Here is the question: someObject.isActive() returns a primitive (lowercase) boolean. The rest of the condition requires Java to autobox it to a Boolean object. Will Java autoboxing create a new instance?
if Java autoboxing creates a new Boolean instance every time, then the comparison to Java’s constant Boolean.FALSE object must always be untrue. It can never come out as true.
The convention if (something == Boolean.FALSE) is used in several places in DiscoveryWorker.
Long story short: if Java autoboxing creates a new Boolean instance every time, this code is rife with potential bugs. Any migrations that we’ve already done with it, may be broken or incomplete.
I decided to publish my answer here hoping that it would help other people.
The reason why this looks confusing is because it is very rare that you would see code like this. When found, it should be deleted on the spot — at the very least because this code requires a long explanation.
There are two Java specs in play here:
“Boxing conversion” and “Boolean Equality”.
Chapter 5.1.7 (“Boxing conversion”) of Java 7 language spec says:
If p is a value of type boolean, then boxing conversion converts p into a reference r of class and type Boolean, such that r.booleanValue() == p
also:
If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
This suggests that autoboxing two identical primitive boolean values does NOT create two object instances.now, here is another Java 7 spec element that is relevant here.
Chapter 15.21.2 (“Boolean Equality Operators == and !=”) of Java 7 language spec says:
If the operands of an equality operator are both of type boolean, or if one operand is of type boolean and the other is of type Boolean, then the operation is boolean equality.
The boolean equality operators are associative.
If one of the operands is of type Boolean, it is subjected to unboxing conversion (§5.1.8).
The result of == is true if the operands (after any required unboxing conversion) are both true or both false; otherwise, the result is false.
in other words, a properly implemented JDK will not create object instances for some primitive values, including true/false. and equality operator will unbox Boolean before comparing it to anything.
And to reiterate — I believe stuff like this should be deleted on sight.