To convert a string to a boolean
value in Java, you can use the Boolean.parseBoolean
method.
The Boolean.parseBoolean
method takes a string as an argument and returns the equivalent boolean
value. If the string is equal to the string "true" (ignoring case), the method returns true
, otherwise it returns false
.
Here is an example of how you can use the Boolean.parseBoolean
method to convert a string to a boolean
value in Java:
String s = "true"; boolean b = Boolean.parseBoolean(s);
This code defines a String
variable called s
and assigns it the value "true", and then uses the Boolean.parseBoolean
method to parse the string into a boolean
value and store it in a boolean
variable called b
. The output of this code will be true
.
You can also use the Boolean.valueOf
method to convert a string to a boolean
value in Java. This method works in the same way as the Boolean.parseBoolean
method, but it returns a Boolean
object instead of a boolean
primitive value.
Here is an example of how you can use the Boolean.valueOf
method to convert a string to a boolean
value in Java:
String s = "true"; Boolean b = Boolean.valueOf(s);
This code defines a String
variable called s
and assigns it the value "true", and then uses the Boolean.valueOf
method to parse the string into a Boolean
object and store it in a Boolean
variable called b
. The output of this code will be a Boolean
object with the value true
.
Note that the Boolean.parseBoolean
and Boolean.valueOf
methods only recognize the strings "true" and "false" (ignoring case) as valid boolean values. If the string contains a different value, the method will return false
. For example, the following code will return false
:
String s = "yes"; boolean b = Boolean.parseBoolean(s); System.out.println(b);
output:
false