Friday, March 17, 2006

To Boolean or not to Boolean

There is no reason to create new Boolean object. In 99.99% cases we are only interested in using a Boolean object that holds either true or false value. The only case where we might need to create a new instance is for instance comparison rather then value comparison (equals()), e.g.

new Boolean(true) == new Boolean(true)

Java Boolean class comes with two constants that will do the job: Boolean.TRUE and Boolean.FALSE.

private Boolean isNegative(int i) {
return new Boolean(i < 0);

Better way:

private Boolean isNegative(int i) {
return i < 0 ? Boolean.TRUE : Boolean.FALSE;

This might be trivial, but can significantly improve performance. Creating new objects is an expensive operation and it also consumes more memory that must be allocated to these objects and then potentially garbage collected.

Second issue that can potentially rise with using Boolean class is how to convert a String value to boolean. Boolean class offers two methods that accept String as a parameter:

  • static boolean getBoolean(String)

  • static Boolean valueOf(String)

Which one to use?

The JavaDoc for the later states: Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

The JavaDoc for getBoolean(String)states: Returns true if and only if the system property named by the argument exists and is equal to the string "true". (Beginning with version 1.0.2 of the JavaTM platform, the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class. If there is no property with the specified name, or if the specified name is empty or null, then false is returned.

People tend to forget this from time to time and tend to use getBoolean(String), especially when require a boolean primitive as outcome. Fortunately, with good tests in place this is discovered and fixed in early development stages.

Therefore use getBoolean(String) only if you need to read system property value as a boolean. For String conversion always use valueOf(String)

String valid = getValidity(); // implemented elsewhere
boolean isValid = Boolean.valueOf(valid).booleanValue();

Any questions? Boolean.FALSE


Hugo Alvarado said...

Thank you! Just what I was looking for.

Christopher Parker said...

Best way:

private boolean isNegative(int i) {
return (i < 0);

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.