Join our newsletter for the latest updates.
Java Program to convert string type variables into boolean

Java Program to convert string type variables into boolean

In this program, we will learn to convert the String type variables into boolean in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Convert string to boolean using parseBoolean()

class Main {
  public static void main(String[] args) {

    // create string variables
    String str1 = "true";
    String str2 = "false";

    // convert string to boolean
    // using parseBoolean()
    boolean b1 = Boolean.parseBoolean(str1);
    boolean b2 = Boolean.parseBoolean(str2);

    // print boolean values
    System.out.println(b1);    // true
    System.out.println(b2);    // false
  }
}

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

Here, Boolean is a wrapper class in Java. To learn more, visit the Java Wrapper Class.


Example 2: Convert string to boolean using valueOf()

We can also convert the string variables into boolean using the valueOf() method. For example,

class Main {
  public static void main(String[] args) {

    // create string variables
    String str1 = "true";
    String str2 = "false";

    // convert string to boolean
    // using valueOf()
    boolean b1 = Boolean.valueOf(str1);
    boolean b2 = Boolean.valueOf(str2);

    // print boolean values
    System.out.println(b1);    // true
    System.out.println(b2);    // false
  }
}

In the above example, the valueOf() method of Boolean class converts the string variables into boolean.

Here, the valueOf() method actually returns an object of the Boolean class. However, the object is automatically converted into a primitive type. This is called unboxing in Java. To learn more, visit Java autoboxing and unboxing.

That is,

// valueOf() returns object of Boolean
// object is converted onto boolean value
boolean b1 = Boolean obj = Boolean.valueOf(str1)