Java Reference
In-Depth Information
static Boolean valueOf(String s) returns TRUE when s equals
"true" , "TRUE" , "True" ,oranyotheruppercase/lowercasecombinationof
these letters. Otherwise, this method returns FALSE .
Caution Newcomers to the Boolean class often think that getBoolean() re-
turns a Boolean object's true/false value. However, getBoolean() returns the
value of a Boolean-based system property—I discuss system properties later in this
chapter. If you need to return a Boolean object's true/false value, use the
booleanValue() method instead.
It is often better to use TRUE and FALSE than to create Boolean objects. For ex-
ample,supposeyouneedamethodthatreturnsa Boolean objectcontainingtruewhen
themethod's double argumentisnegative,orfalsewhenthisargumentiszeroorpos-
itive. You might declare your method like the following isNegative() method:
Boolean isNegative(double d)
{
return new Boolean(d < 0);
}
Although this method is concise, it unnecessarily creates a Boolean object. When
themethodiscalledfrequently,many Boolean objectsarecreatedthatconsumeheap
space.Whenheapspacerunslow,thegarbagecollectorrunsandslowsdowntheapplic-
ation, which impacts performance.
The following example reveals a better way to code isNegative() :
Boolean isNegative(double d)
{
return (d < 0) ? Boolean.TRUE : Boolean.FALSE;
}
This method avoids creating Boolean objects by returning either the precreated
TRUE or FALSE object.
Tip You should strive to create as few objects as possible. Not only will your ap-
plications havesmaller memoryfootprints,they'll performbetter because thegarbage
collector will not run as often.
Search WWH ::




Custom Search