How to convert String object to Boolean Object?
To convert a String
object to a Boolean
object in Java, you can use the Boolean.valueOf
method:
String str = "true";
Boolean bool = Boolean.valueOf(str); // bool is now a Boolean object with the value true
This method returns a Boolean
object with the value true
if the string is equal to "true" (ignoring case), and a Boolean
object with the value false
if the string is equal to "false" (ignoring case). If the string is not equal to "true" or "false" (ignoring case), it will throw a NumberFormatException
.
Alternatively, you can use the Boolean.parseBoolean
method:
String str = "true";
boolean bool = Boolean.parseBoolean(str); // bool is now a boolean primitive with the value true
This method returns a boolean primitive with the value true
if the string is equal to "true" (ignoring case), and a boolean primitive with the value false
if the string is equal to "false" (ignoring case). If the string is not equal to "true" or "false" (ignoring case), it will return false
.
You can also use the Boolean.getBoolean
method to get the boolean value of a system property:
String str = "java.awt.headless";
boolean bool = Boolean.getBoolean(str); // bool is now the boolean value of the system property "java.awt.headless"
This method returns the boolean value of the system property with the specified name. If the system property does not exist or its value is not equal to "true" (ignoring case), it will return false
.