Java Convert String to boolean

Tags: String boolean

In this Java core tutorial we learn how to convert a String value into boolean value in Java programming language.

Table of contents

  1. Convert String to boolean using Boolean.parseBoolean() method
  2. Convert String to boolean using Boolean.valueOf() method

Convert String to boolean using Boolean.parseBoolean() method

The first solution, we can use the Boolean.parseBoolean() method to parse a String value into boolean as following Java example program.

StringToBooleanExample1.java

public class StringToBooleanExample1 {
    public static void main(String... args) {
        String stringValue1 = "true";
        String stringValue2 = "false";

        boolean booleanValue1 = Boolean.parseBoolean(stringValue1);
        boolean booleanValue2 = Boolean.parseBoolean(stringValue2);

        System.out.println(booleanValue1);
        System.out.println(booleanValue2);
    }
}
The output as below.
true
false

Convert String to boolean using Boolean.valueOf() method

The second solution, we can use the Boolean.valueOf() method to instantiate a boolean value from a String as below Java code.

StringToBooleanExample2.java

public class StringToBooleanExample2 {
    public static void main(String... args) {
        String stringValue1 = "true";
        String stringValue2 = "false";

        boolean booleanValue1 = Boolean.valueOf(stringValue1);
        boolean booleanValue2 = Boolean.valueOf(stringValue2);

        System.out.println(booleanValue1);
        System.out.println(booleanValue2);
    }
}
The output as below.
true
false

Happy Coding 😊

Java Convert boolean to String