How to convert String
object to Boolean
object?
Well, as now in Jan, 2018, the best way for this is to use apache's BooleanUtils.toBoolean
.
This will convert any boolean like string to boolean, e.g. Y, yes, true, N, no, false, etc.
Really handy!
Visit http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx
This will give you an idea of what to do.
This is what I get from the Java documentation:
Method Detail
parseBoolean
public static boolean parseBoolean(String s)
Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not
null
and is equal, ignoring case, to the string "true
".Parameters:
s
- the String containing the boolean representation to be parsedReturns: the boolean represented by the string argument
Since: 1.5
Beside the excellent answer of KLE, we can also make something more flexible:
boolean b = string.equalsIgnoreCase("true") || string.equalsIgnoreCase("t") ||
string.equalsIgnoreCase("yes") || string.equalsIgnoreCase("y") ||
string.equalsIgnoreCase("sure") || string.equalsIgnoreCase("aye") ||
string.equalsIgnoreCase("oui") || string.equalsIgnoreCase("vrai");
(inspired by zlajo's answer... :-))
Use the Apache Commons library BooleanUtils class:
String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}
Result:
Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false
To get the boolean value of a String, try this:
public boolean toBoolean(String s) {
try {
return Boolean.parseBoolean(s); // Successfully converted String to boolean
} catch(Exception e) {
return null; // There was some error, so return null.
}
}
If there is an error, it will return null. Example:
toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null
Boolean b = Boolean.valueOf(string);
The value of b
is true if the string is not a null and equal to true
(ignoring case).