Convert String to boolean in java

Posted on Updated on

In Java programming, developers often comes in the situation where they have to convert String into different datatype like int, double, boolean and so on. In previous blog, we have written how one can convert String to int in java. Here in this blog we will see how to convert String to boolean in java.

Followings are different ways to convert String to boolean:

  1. Using Boolean.parseBoolean(str)
  2. Using Boolean.valueOf(str)
  3. Using BooleanUtils.toBoolean(str)

1) Using Boolean.parseBoolean(str)

The most flexible and easy ways to convert String to boolean. This method returns boolean(primitive data type), however autoboxing can be use to convert boolean to Boolean, but it has a performance cost. You must be careful while using Boolean.parseBoolean(str) as it returns false if the String is not equal to “true” (the case is ignored).Below code demonstrate example to convert String to boolean using Boolean.parseBoolean(str).

Output

2) Using Boolean.valueOf(str)

Another way to convert String to boolean is using Boolean.valueOf(str) method which follows the Factory method design pattern in java. This method too returns false if the String is not equal to “true” (the case is ignored).Below code demonstrate example to convert String to boolean using Boolean.valueOf(str).

Output

3) Using BooleanUtils.toBoolean(str)

Methods discussed above returns true only when String is “true”(the case is ignored) while in practical scenarios we have to convert other Strings like “yes”, “Y” and so on to true. For such scenarios, BooleanUtils class is an excellent choice. To use BooleanUtils class you have to add commons-lang.jar in your project’s classpath or if you are using maven add below dependency to pom.xml file.

Code to demonstrate example to convert String to boolean using BooleanUtils.

Output

Stay tuned for more updates !!!

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.