I am surprised to know that getBoolean()
and valueOf()
method returns different results for the same input string.
I have tried to pass the
class Boo1
{
public static void main(String[] args)
{
System.setProperty("true","true");
System.setProperty("false","true");
boolean d=Boolean.getBoolean("true");
System.out.println(d);
}
}
I too found this issue recently when using Boolean.getBoolean() . In addition if you want to have a null check you can use Boolean.parseBoolean which will return false in case of nulls
The API-documentation is your friend.
Boolean.getBoolean probably doesn't do what you think it does:
Returns true if and only if the system property named by the argument exists and is equal to the string "true".
Boolean.valueOf is probably what you're looking for:
The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Boolean.getBoolean
must be the worst placed method in java. One of the big WTF.
Why wasn't it placed in System
or Properties
or whatever?
So to answer your question - yes, it is a very confusing thing and you can just click on the method in your IDE to see the code or read the javadoc.
Here's the source code:
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = toBoolean(System.getProperty(name));
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
return result;
}
The javadoc of getBoolean clearly state that it searches the System Properties. The value that you pass to it is the name of the system property, not a "true" or "false" string.
E.g., `var b = Boolean.getBoolean("some.property");