Java Convert String to boolean
In this Java core tutorial we learn how to convert a String value into boolean value in Java programming language.
Table of contents
- Convert String to boolean using Boolean.parseBoolean() method
- 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);
}
}
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);
}
}
true
false
Happy Coding 😊