Convert String to boolean in java

By | May 25, 2020

Convert String to boolean in java:

In this tutorial, you are going to learn how to convert string to boolean in java. We can achieve it in two ways.

1 Boolean.parseBoolean() method

2 Boolean.valueOf() method

Both the methods are null safe. It means if you pass a value other than true or false, it won’t throw null pointer exception. Instead it will return false. 

 

1. Boolean.parseBoolean():

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”.
Example: Boolean.parseBoolean(“True”) returns true.
Example: Boolean.parseBoolean(“yes”) returns false.
Parameters:
s – the String containing the boolean representation to be parsed
Returns:
the boolean represented by the string argument

Example:

Output:

2. Boolean.valueOf():

Returns a Boolean with a value represented by the specified string. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string “true”.
Parameters:
s – a string.
Returns:
the Boolean value represented by the string.

Example:

Output:

 

Recommended Posts:

How to remove last element from an ArrayList in Java

Java program to find largest number in an array

 

Tags: Convert String to boolean in java

 

Leave a Reply

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