How to convert a String to boolean in Java

We can convert a String to a primitive boolean using the Boolean.parseBoolean method or to a wrapped Boolean class using the Boolean.valueOf.

Info: By default the converted String will only convert "true" and "false" to the correct representation of a Boolean. Every other value passed to the Boolean.parseBoolean or Boolean.valueOf methods results in "false". If you want to convert a custom value like: "1". to a boolean you can do the following:

String isNumberBoolean = "1";
Boolean isBoolean = "1".equals(isNumberBoolean);

Convert String to boolean using Boolean.parseBoolean

The Boolean.parseBoolean method is used to convert a String to primitive boolean.

String isBoolean = "true";
boolean convertedIsBoolean = Boolean.parseBoolean(isBoolean);
System.out.println("Convert String to boolean: " + convertedIsBoolean);

String isNumberBoolean = "1";
boolean convertedIsNumberBoolean = Boolean.parseBoolean(isNumberBoolean);
System.out.println("Convert String Number to boolean: " + convertedIsNumberBoolean);

String isInvalidBoolean = "-abc";
boolean convertedIsInvalidBoolean = Boolean.parseBoolean(isInvalidBoolean);
System.out.println("Convert String string to boolean: " + convertedIsInvalidBoolean);

The previous will generate the following output.

Convert String to boolean: true
Convert String Number to boolean: false
Convert String string to boolean: false

Convert String to Boolean using Boolean.valueOf

The Boolean.valueOf method is used to convert a String to a wrappedBoolean.

String isBoolean = "true";
Boolean convertedIsBoolean = Boolean.valueOf(isBoolean);
System.out.println("Convert String to boolean: " + convertedIsBoolean);

String isNumberBoolean = "1";
Boolean convertedIsNumberBoolean = Boolean.valueOf(isNumberBoolean);
System.out.println("Convert String number to boolean: " + convertedIsNumberBoolean);

String isInvalidBoolean = "-abc";
Boolean convertedIsInvalidBoolean = Boolean.valueOf(isInvalidBoolean);
System.out.println("Convert String string to boolean: " + convertedIsInvalidBoolean);

The previous will generate the following output.

Convert String to boolean: true
Convert String number to boolean: false
Convert String string to boolean: false

References

Download

You may also like...