1. Overview

In this tutorial, we’ll explore the different ways we can use Java’s Boolean class to convert a String into a boolean.

2. Boolean.parseBoolean()

Boolean.parseBoolean() allows us to pass in a String and receive a primitive boolean.

First, let’s write a test to see how parseBoolean() converts a String with the value true:

assertThat(Boolean.parseBoolean("true")).isTrue();

Of course, the test passes.

In fact, the semantics of parseBoolean() are so clear that IntelliJ IDEA warns us that passing the string literal “true” is redundant.

In other words, this method is excellent for turning a String into a boolean.

3. Boolean.valueOf()

Boolean.valueOf() also lets us pass in a String, but this method returns a Boolean class instance instead of a primitive boolean.

We can see that this method also succeeds in converting our String:

assertThat(Boolean.valueOf("true")).isTrue();

This method actually uses parseBoolean() to do its String conversion in the background, and simply uses the result to return a statically defined Boolean instance.

Therefore, this method should only be used if the returned Boolean instance is needed. If only a primitive result is needed, it’s more performant to stick with using parseBoolean() directly.

#java #java string

Converting a Java String Into a Boolean
1.45 GEEK