In Java, to convert a string to a Boolean, we can use Boolean.parseBoolean(string) to convert a string to a primitive Boolean, or Boolean.valueOf(string) to convert it to a Boolean object. The Boolean data type only holds two possible values which are true and false. If the string equals "true" (ignoring case), it converts to true, otherwise, it converts to false. In this article, we will learn how to convert a String to a Boolean in Java with examples.
Note: In Java, only true and false are returned as boolean not 0 and 1.
Example:
Below is a simple example of converting a String to a primitive boolean by using the Boolean.parseBoolean() method.
// Java Program to Convert String to Boolean
// using parseBoolean() Method
public class StringToBoolean {
public static void main(String[] args) {
// Define a custom string
String s = "true";
System.out.println("String: " + s);
// Convert String to boolean
boolean b = Boolean.parseBoolean(s);
System.out.println("Boolean: " + b);
}
}
Output
String: true Boolean: true
Syntax of Boolean.parseBoolean() Method
boolean boolValue = Boolean.parseBoolean(String s)
Parameter:
- s: String that contains true (case-insensitive) or false.
Return Type:
- It returns
true,if the string (ignoring case) is"true". - It returns
false,for any other input.
Other Way to Convert String to boolean
In addition to using Boolean.parseBoolean() method, there is another way to convert a string to a boolean in Java. We will discuss below this method with example:
Using Boolean.valueOf() Method
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 of Boolean.valueOf() method
boolean boolValue = Boolean.valueOf(String str)
Example:
// Java Program to Convert a String to Boolean Object
// using valueOf() method of Boolean Class
class GFG {
// Method 1
// To convert a string to its boolean object
public static boolean stringToBoolean(String s)
{
// Converting a given string
// to its boolean object
// using valueOf() method
boolean b1 = Boolean.valueOf(s);
// Returning boolean object
return b1;
}
// Method 2
// Main driver method
public static void main(String args[])
{
// Given input string 1
String s = "yes";
// Printing the desired boolean
System.out.println(stringToBoolean(s));
// Given input string 2
s = "true";
// Printing the desired boolean
System.out.println(stringToBoolean(s));
// Given input string 3
s = "false";
// Printing the desired boolean
System.out.println(stringToBoolean(s));
}
}
Output
false true false
Points to Remember:
TheBoolean.parseBoolean()method returns a primitiveboolean.TheBoolean.valueOf()method returns aBooleanobject.- Any string other than
"true"(case-insensitive) will result infalse.