Java – how to check if a String is a boolean!

I stumbled upon this “problem” regularly, for example I have a String value and want to check if this can be parsed to a boolean.

Boolean.getBoolean(String name) – javadocs

Returns true if and only if the system property named by the argument exists and is equal to the string "true".

here you can see that everything is false (probably because of the system property)

Boolean.parseBoolean(Srting s) – javadocs

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

this is interesting, here you can see that we are parsing the string and always get false except when the String is “true”. In this Case we cant distinguish now if the String is a boolean or not, because we get only true or false even if the String is neither true nor false.

Boolean.valueOf(String s) – javadocs

Returns a Boolean with a value represented by the specified string.

Same result with valueOf, we still get false even though it is not a boolean.

Easy solution

Personally I like to have a method to check if the String is a boolean so that I have only two lines of code for it. If I only use the if statement to parse the String to a boolean I can’t be sure if it is really a boolean (especially important if you need to handle some user input in some configuration files) like we could see above. The Solution is pretty easy but I thought there is some easier way. All you have to do is to check if the String equals to true or false.

And there you have it, even if you have lower or uppercase versions of true and false you will always know if it is a boolean or not.

 

Leave a Reply

Your email address will not be published. Required fields are marked *