Convert a String to Boolean in Java

In this post, we will discuss how to convert a String to Boolean in Java. In other words, return the Boolean value represented by a specified string.


 

1. Boolean.valueOf()

The simplest solution is to use Boolean.valueOf() which returns Boolean.TRUE if the specified string is equal to “true”, case ignored.

 

Download   Run Code

Output:

true
false

 

2. Boolean.parseBoolean()

Another plausible way to get the boolean value of a String is to use Boolean.parseBoolean() method which returns primitive boolean and hence offers better performance than Boolean.valueOf() method.

 

Download   Run Code

Output:

true
false

 

3. String.equalsIgnoreCase()

The final approach is to use String.equalsIgnoreCase() and compares the specified String with the String “true” as shown below:

 

Download   Run Code

Output:

true
false

 

All three approach discussed above are different but are related. Internally, Boolean.valueOf() method makes call to Boolean.parseBoolean() method, which in turn uses String.equalsIgnoreCase().

The problem with above methods is that they all return false when the specified string is null or is not equal to the string “true”, case ignored. One solution is to ensure that the specified string is valid or not in advance and returns a null when string is invalid.

 

Download   Run Code

Output:

true
true
false
null
null

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of