How to Convert String to boolean in Java

There are two methods to convert String to boolean:

  • Using parseBoolean(string) method
  • Using valueOf(string) method

If the string contains “True,” “true,” or “TRUE,” it returns Boolean true. It returns Boolean false if the string doesn’t contain “True,” “true,” or “TRUE.” It is case insensitive.  Both the above methods are null safe; it means they will return false if you pass null. For example:

boolean b1=Boolean.parseBoolean(null);

Using parseBoolean(string)

It converts String into Boolean primitive. It is the static method of the Boolean wrapper class. It doesn’t throw an exception if you pass any string value other than true and false. For example, if you pass “Yes,” it will return false. The signature of the method is given below:

Where str is the string to be converted into Boolean primitive.

Example

In the following example, we have taken two variables str1 and str2 of String type that contains “TRUE” and “true3” respectively. b1 and b2 are two variable that stores the primitive Boolean value of the string str1 and str2, respectively. Boolean is the wrapper class, and it invokes parseBoolean(string) method of the class. The method parses a string argument and converts it to Boolean primitive. The first println statement prints the Boolean value of the string str1, i.e., true and the second println statement prints the Boolean value of the string str2, i.e., false.

Output

Using valueOf(string)

It also works similar to parseBoolean(string) method. The valueOf(string) method converts a string into the Boolean object. It returns the instance of the Boolean class instead of primitive Boolean value. It returns true for a non-null string and returns false for everything else. Boolean instances are immutable, so you should always use valueOf(string) method. The signature of the method is given below.

public static Boolean valueOf(String str)

Example

In the following example, we have taken two variables str1 and str2 of String type that contains “TRUE” and “” (null) respectively. b1 and b2 are two variable that stores the primitive Boolean value of the string str1 and str2 respectively. Boolean is the wrapper class and it invokes valueOf(string) method of the class. The method parses a string argument and converts it to Boolean primitive. The first println statement prints the Boolean value of the string str1 i.e. true and the second println statement prints the Boolean value of the string str2, i.e., false.

Output

Pin It on Pinterest

Share This