What is the difference between false and Boolean.FALSE?

Ahmad Dwaik 'Warlock' picture Ahmad Dwaik 'Warlock' · Nov 20, 2013 · Viewed 25.1k times · Source

In C++ windows.h FALSE is defined as integer which makes sense for some special logic cases, but in Java java.lang.Boolean.FALSE is defined as boolean and assigned to false
public static final Boolean FALSE and I've seen some people use it.

My question: is there a performance difference between false and Boolean.FALSE? in general why do people go and Boolean.FALSE?

Answer

Jason C picture Jason C · Nov 20, 2013

See http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html.

Boolean.TRUE and Boolean.FALSE are not boolean, they are Boolean. They are static instances of the two Boolean wrapper objects that correspond to the boolean values true and false.

Boolean is similar to an enum. The TRUE and FALSE instances are the instances returned by Boolean.valueOf().

As for performance of primitive vs. wrapper; there is no difference that you would ever need to be concerned about. The TRUE and FALSE static instances help performance a bit, and the javadocs recommend using Boolean.valueOf() as opposed to new Boolean(...) for that reason. The true and false boolean values are a little "lower level", but if you are storing them in a Boolean (as opposed to boolean) anyways it's irrelevant.

You should use whichever makes the most sense for your code and leads to the best readability (and definitely don't start going down the path of thinking of microoptimizations like primitive vs. wrapper types). If you are using a Boolean, use the object values. If you are using a boolean, use the primitive values. If you are deciding between Boolean vs boolean, use whatever is more appropriate (e.g. a Boolean can be null, which may be useful, and also you can't use primitive types for generic type parameters; on the other hand, a boolean can never be null which could be equally useful).

Also note that auto boxing converts the primitive types to one of those two static Boolean instances, e.g.:

Boolean a = true;
assert(a == Boolean.TRUE);



As an aside, since you mentioned it: FALSE is defined in windows.h for two reasons: 1) Because windows.h has been in use since C-only days, and C does not have a native bool type, and 2) it is traditional Microsoft practice to define data types and values with known, explicit sizes and values, esp. for passing data to Windows API functions across DLL boundaries (beyond the scope of this question) and for integrating with other languages that have different representations of "true" and "false". It is entirely unrelated to the reasons for Boolean.FALSE in Java.