How to check if String value is Boolean type in Java?
130,182
Solution 1
- parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false
- valueOf(String) ditto, returns the canonical Boolean Objects
- getBoolean(String) is a red herring; it fetches the System property of the given name and compares that to "true"
There exists no method to test whether a String encodes a Boolean; for all practical effects, any non-"true"-String is "false".
Solution 2
return "true".equals(value) || "false".equals(value);
Solution 3
Apache commons-lang3 has BooleanUtils with a method toBooleanObject:
BooleanUtils.toBooleanObject(String str)
// where:
BooleanUtils.toBooleanObject(null) = null
BooleanUtils.toBooleanObject("true") = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on") = Boolean.TRUE
BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
BooleanUtils.toBooleanObject("off") = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
BooleanUtils.toBooleanObject("blue") = null
Solution 4
if ("true".equals(value) || "false".equals(value)) {
// do something
} else {
// do something else
}
Solution 5
Here's a method you can use to check if a value is a boolean:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Examples of using it:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
Related videos on Youtube
Author by
Ragnar
Updated on January 11, 2020Comments
-
Ragnar over 4 years
I did a little search on this but couldn't find anything useful.
The point being that if String value is either "true" or "false" the return value should be true. In every other value it should be false.
I tried these:
String value = "false"; System.out.println("test1: " + Boolean.parseBoolean(value)); System.out.println("test2: " + Boolean.valueOf(value)); System.out.println("test3: " + Boolean.getBoolean(value));
All functions returned false :(
-
moxn over 14 yearsEven if you set
value = "true"
? -
moxn over 14 yearsAnyway, if you try one of the proposed approaches you should use String.equalsIgnoreCase(String s) to be on the safe side.
-
Alexander Pogrebnyak over 14 yearsDid you try this: tinyurl.com/ycovuqg
-
yashan over 14 yearsIt appears that you are using these methods incorrectly. Please take a look at the Java docs for Boolean. j2ee.me/javase/6/docs/api/java/lang/Boolean.html
-
kdgregory over 14 years@moxn - Based on the comment for a response, it appears that the OP wants to deal with strings that might need to be trimmed. However, it's certainly bizarre to complain that "false" is always parsed as false.
-
Ragnar over 14 yearsKhm, I'm aware what getBoolean,valueOf and parseBoolean functions do, Thank You! However the question is not about these functions. I wanted to know how lazily check if the string value is boolean. I quess I have to write some function that wraps "true".equals(value) || "false".equals(value).
-
Alex Feinman over 14 yearsRagnar, the reason you're not finding it is that everyone has a different definition of what a boolean should be in string form. Is "TRUE" valid"? What about "True"? "TRUE" in double-byte characters? For perl hackers, having "1" not be true is offensive. :) So your method is going to have to be explicit about what it desires.
-
-
Ben James over 14 yearsInstead of hard-coding
"true"
and"false"
, you can usetrue.toString
andfalse.toString
, just in case the string representations of "true" and "false" ever change ;) -
Andreas Dolk over 14 yearsYou could wrap the return statement into an try/catch construct, catch NPE and handle this exceptional state to return the real ... just kidding ;-)
-
Thorsten Dittmar over 14 yearsIn other languages, "1" and "0" are also considered valid for boolean string parsing, so I don't quite like the "hardcode true and false"-approach. OTOH the OP introduced the restriction to true and false, so well...
-
Ragnar over 14 yearsI was hoping to avoid this, since the input value could also be " true" or "True" or "TRUE" etc.
-
Ragnar over 14 yearsI kind of figured it out too.
-
Stephen C over 14 years@lutz - bad advice. A
null
is almost certainly a bug and should result in an NPE. Testing fornull
to avoid the NPE is almost certainly going to obscure the bug. You should only test fornull
if it is explicitly stated thatnull
has meaning. -
moxn over 14 years@Ragnar As I pointed out in a comment above, you should use String.equalsIgnoreCase(String s).
-
Ragnar over 14 yearsOK, this what I needed to know. I wonder why it is practical to have have any non-"true"-String as false? I mean in my mind valid inputs should be true and false and everything else is just not boolean input.
-
Ragnar over 14 years@moxn Thanks. I'll probably just wrap this into one funtion to check both true and false so I get bit cleaner code.
-
mfx over 14 yearsTrue, one could imagine a "BooleanFormatException" Exception, in analogy to the NumberFormatException that occurs when you try to parse a non-number String. I suppose it was deemed unnecessary at the time the library was written (1996!), for the targeted environments (embedded systems like set-top boxes and browsers).
-
Peymankh over 11 yearsWell there is no BooleanFormatException, but by using Apache Commons' BooleanUtils.toBooleanObject, if a string cannot be parsed, a null value will be returned, which can be quite useful.
-
Stachu almost 9 yearsQuit teasing the Java dev with C# code. That said, with Optional in Java 8, may be useful to write a little wrapper, where Optional.empty indicates non-bool.
-
Thorsten Dittmar almost 9 yearsIf you read my answer carefully you will see that I'm not teasing him with C# code, but I'm suggesting he looks for methods in Java that do something similar to the methods in C#, as they conveniently both validate and convert. I've not used Java in a while, as I said, so I'm not sure whether features like that have been introduced.
-
Stachu almost 9 yearsIt was a joke. "teasing."
-
Thorsten Dittmar almost 9 yearsSorry, didn't get that ;-)
-
José almost 9 yearsThis utility is not really helpful in this case since the following will return a boolean set to false: BooleanUtils.toBoolean("spaceship");
-
VVB over 7 yearsNice study. Only thing is, it does not work with Boolean.valueOf() too.
-
Stefan Hendriks over 7 yearscould you be a bit more specific what you're trying and what does not work?
-
Stefan Hendriks over 7 yearsunless you would expect a null value to be parsed. Then you could swap around the checks "false".equals(value) || "true".equals(value). Then again, you get casing issues.
-
Noumenon about 6 yearsThere is also toBoolean, which returns false where this returns null. Seems a bit safer, but this lets you check for whether the object doesn't exist.