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
Share:
130,182

Related videos on Youtube

Ragnar
Author by

Ragnar

Updated on January 11, 2020

Comments

  • Ragnar
    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
      moxn over 14 years
      Even if you set value = "true"?
    • moxn
      moxn over 14 years
      Anyway, if you try one of the proposed approaches you should use String.equalsIgnoreCase(String s) to be on the safe side.
    • Alexander Pogrebnyak
      Alexander Pogrebnyak over 14 years
      Did you try this: tinyurl.com/ycovuqg
    • yashan
      yashan over 14 years
      It 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
      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
      Ragnar over 14 years
      Khm, 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
      Alex Feinman over 14 years
      Ragnar, 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
    Ben James over 14 years
    Instead of hard-coding "true" and "false", you can use true.toString and false.toString, just in case the string representations of "true" and "false" ever change ;)
  • Andreas Dolk
    Andreas Dolk over 14 years
    You 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
    Thorsten Dittmar over 14 years
    In 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
    Ragnar over 14 years
    I was hoping to avoid this, since the input value could also be " true" or "True" or "TRUE" etc.
  • Ragnar
    Ragnar over 14 years
    I kind of figured it out too.
  • Stephen C
    Stephen C over 14 years
    @lutz - bad advice. A null is almost certainly a bug and should result in an NPE. Testing for null to avoid the NPE is almost certainly going to obscure the bug. You should only test for null if it is explicitly stated that null has meaning.
  • moxn
    moxn over 14 years
    @Ragnar As I pointed out in a comment above, you should use String.equalsIgnoreCase(String s).
  • Ragnar
    Ragnar over 14 years
    OK, 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
    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
    mfx over 14 years
    True, 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
    Peymankh over 11 years
    Well 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
    Stachu almost 9 years
    Quit 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
    Thorsten Dittmar almost 9 years
    If 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
    Stachu almost 9 years
    It was a joke. "teasing."
  • Thorsten Dittmar
    Thorsten Dittmar almost 9 years
    Sorry, didn't get that ;-)
  • José
    José almost 9 years
    This utility is not really helpful in this case since the following will return a boolean set to false: BooleanUtils.toBoolean("spaceship");
  • VVB
    VVB over 7 years
    Nice study. Only thing is, it does not work with Boolean.valueOf() too.
  • Stefan Hendriks
    Stefan Hendriks over 7 years
    could you be a bit more specific what you're trying and what does not work?
  • Stefan Hendriks
    Stefan Hendriks over 7 years
    unless 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
    Noumenon about 6 years
    There 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.