Working with Boolean values

There is more to working with Boolean values than often meets the eye. Many a Java developer has run into a brick wall when setting and/or retrieving Boolean values.

The following code snippet illustrates a common Boolean conundrum:

boolean b = true;

getBoolean(b);

The above code will return false in every case. Why?

Here's what java.sun.com has to say about getBoolean(): "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 Java platform, the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class."

A better choice of syntax would be

boolean b = true;

(Boolean.valueOf(b)).booleanValue();

This returns the proper Boolean value sought. The method valueOf() creates a new Boolean object that contains the value true if the argument is not null and is equal to the string "true."

Correction

In the May 28, 2001, Java TechMail, we stated that, in reference to the first code sample, "The user has actually created two vectors—one outside of the 'for' loop and one within!" This should have read "The user has actually created two vectors—one outside of the constructor and one within!"

Additionally, for compatibility purposes, the "void" return value should be removed from the corrected code sample. We apologize for any inconvenience these issues may have caused.

Hosted by www.Geocities.ws

1