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

There are several ways to convert a String to a Boolean in Java, depending on whether we want a primitive boolean value or a Boolean object. Here are some of the most common methods:

1. Using Boolean.parseBoolean() method

The simplest and efficient solution to get the boolean value of a string is to use the Boolean.parseBoolean() method, which returns a primitive boolean value that is true if the string argument is equal to "true" (ignoring case), and false otherwise. This method offers the best performance than all other methods.

Download  Run Code

2. Using Boolean.valueOf() method

Another plausible way is to use the Boolean.valueOf(), which returns Boolean.TRUE if the specified string is equal to “true”, case ignored. This method returns a Boolean object that wraps the result of parseBoolean(). This method should be used over the parseBoolean() method only if we need a Boolean object instead of a primitive boolean value.

Download  Run Code

3. Using String.equalsIgnoreCase() method

The final approach to convert a String to a boolean value in Java is using the String.equalsIgnoreCase() method. The idea is to compare the string with the literal "true" and return the result of the comparison. For example, we can write a method like below. The similar method is used by the parseBoolean() method for comparison.

Download  Run Code

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

Download  Run Code

 
We can also use the Boolean() constructor that takes a string argument and creates a new Boolean object from it, using the same logic as parseBoolean() method. However, this method is deprecated since Java 9, and marked for removal in future releases. Therefore, is not recommended to use this method. It is better to use the parseBoolean() method to convert a string to a boolean primitive, or the valueOf() method to convert a string to a Boolean object.

That’s all about converting a String to a Boolean in Java.