Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getBoolean(String str) and valueOf(String str) of Boolean class gives different output

Tags:

java

boolean

I am surprised to know that getBoolean() and valueOf() method returns different results for the same input string.

I have tried to pass the "true" to both the methods. But getBoolean() gives me false output whereas valueOf() gives me right output that is true. Why?

like image 689
Mahendra Athneria Avatar asked Apr 07 '11 12:04

Mahendra Athneria


People also ask

What is the result for Boolean valueOf hello ); true?

The valueOf() method returns a Boolean instance corresponding to 'b' or to String 's'. It returns true, if the defined Boolean value (b) or String value(s) is true. It returns false, if the String contains any value other than true.

What is Boolean valueOf?

valueOf(boolean b) returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, this method returns Boolean. TRUE; if it is false, this method returns Boolean.


2 Answers

                                     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".

like image 126
aioobe Avatar answered Sep 28 '22 04:09

aioobe


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");

like image 40
Yoni Avatar answered Sep 28 '22 05:09

Yoni