In this tutorial, we'll explore the different ways we can use Java's Boolean class to convert a String into a boolean.
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:
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.
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:
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.
Boolean.getBoolean() is a third method that accepts a String and returns a boolean.
Without looking at the documentation or the implementation of this method, one might reasonably assume that this method is also for converting its String argument into a boolean:
assertThat(Boolean.getBoolean("true")).isTrue(); // this test fails!
The reason that this test fails is that the String argument is supposed to represent the name of a boolean system property.
By defining the system property:
Finally, the test passes. Inspecting the implementation of this method reveals that it, too, uses the parseBoolean() method to do its String conversion.
Note that getBoolean() is literally a shortcut for parseBoolean(System.getProperty(“true”)), meaning that we shouldn't be misled by the name.
Therefore, the only way Boolean.getBoolean(“true”); will ever return true is if there exists a system property called “true” and its value parses into true.
In this short tutorial, we have seen the key differences between Boolean.parseBoolean(), Boolean.valueOf(), and Boolean.getBoolean().
While parseBoolean() and valueOf() both convert a String into a boolean, it's important to remember that Boolean.getBoolean() does not.
The source code with all the examples in this tutorial can be found over on Github.
res – REST with Spring (eBook) (everywhere)