Java Program to Convert String to Boolean
Last Updated :
16 Apr, 2022
To convert String to boolean in Java, you can use Boolean.parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean.valueOf(string) method.
Boolean data type consists of only two values i.e true and false. If the string is true (ignoring case), the Boolean equivalent will be true, else false.
Tip: In Java, only true and false are returned as boolean not 0 and 1.
Example:
Input: str = "true"
Output: true
Explanation: The boolean equivalent of true is true itself.
Input: str = "false"
Output: false
Explanation: The boolean equivalent of false is false itself.
Input: str = "yes"
Output: false
Explanation: The boolean equivalent of yes is false since the given value is not equal to true.
This is the most common method to convert String to boolean. This method is used to convert a given string to its primitive boolean value. If the given string contains the value true ( ignoring cases), then this method returns true. If the string contains any other value other than true, then the method returns false.
Syntax:
boolean boolValue = Boolean.parseBoolean(String str)
Example :
Java
class GFG {
public static boolean stringToBoolean(String str)
{
boolean b1 = Boolean.parseBoolean(str);
return b1;
}
public static void main(String args[])
{
String str = "yes" ;
System.out.println(stringToBoolean(str));
str = "true" ;
System.out.println(stringToBoolean(str));
str = "false" ;
System.out.println(stringToBoolean(str));
}
}
|
2. Using valueOf() Method of Boolean Class
It is similar to the above method as discussed just a little difference lies as it returns a boolean object instead of a primitive boolean value.
Syntax:
boolean boolValue = Boolean.valueOf(String str)
Example:
Java
class GFG {
public static boolean stringToBoolean(String str)
{
boolean b1 = Boolean.valueOf(str);
return b1;
}
public static void main(String args[])
{
String str = "yes" ;
System.out.println(stringToBoolean(str));
str = "true" ;
System.out.println(stringToBoolean(str));
str = "false" ;
System.out.println(stringToBoolean(str));
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...