Java Program to Convert String to Boolean

In this java program, we will learn how to convert a string variable to boolean. The boolean data type has only two possible values true and false. If the string is true (ignoring case), the Boolean equivalent will be true, else false.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Convert String to Boolean using parseBoolean() Method

To convert String into Boolean object, we can use Boolean.valueOf(string) method which returns instance of Boolean class. This is the most common method to convert String to boolean. If the given string contains the value true (ignoring cases), then this method returns true. For any other string value except "true" it returns boolean false.

The parseBoolean() is the static method of Boolean class. Here is the syntax of parseBoolean method.

boolean boolValue = Boolean.parseBoolean(String str)

public class StringToBoolean {
  public static void main(String[] args) {
    // Initialize string variables
    String trueStr = "true";
    String falseStr = "false";

    boolean trueVal = Boolean.parseBoolean(trueStr);
    boolean falseVal = Boolean.parseBoolean(falseStr);

    System.out.println(trueVal);
    System.out.println(falseVal);
  }
}
Output
true
false

In the above program, we used parseBoolean() method of the Boolean class to convert the string variables into corresponding boolean value.


Java Program to Convert String to Boolean using valueOf() Method

The Boolean.valueOf() method converts string into Boolean object. It is similar to the parseBoolean method, only difference lies as it returns a Boolean object instead of a primitive boolean value. Here is the syntax of Boolean.valueOf() method.

boolean boolValue = Boolean.valueOf(String str) 

public class StringToBoolean2 {
  public static void main(String[] args) {
    // Initialize string variables
    String trueStr = "true";
    String falseStr = "false";

    Boolean trueObj = Boolean.valueOf(trueStr);
    Boolean falseObj = Boolean.parseBoolean(falseStr);

    System.out.println(trueObj);
    System.out.println(falseObj);
  }
}
Output
true
false