[java] How to check if String value is Boolean type in Java?

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 :(

This question is related to java string boolean

The answer is


if ("true".equals(value) || "false".equals(value)) {
  // do something
} else {
  // do something else
}

Actually, checking for a Boolean type in a String (which is a type) is impossible. Basically you're asking how to do a 'string compare'.

Like others stated. You need to define when you want to return "true" or "false" (under what conditions). Do you want it to be case(in)sensitive? What if the value is null?

I think Boolean.valueOf() is your friend, javadoc says:

Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.


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

I suggest that you take a look at the Java docs for these methods. It appears that you are using them incorrectly. These methods will not tell you if the string is a valid boolean value, but instead they return a boolean, set to true or false, based on the string that you pass in, "true" or "false".

http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html


  function isBooleanString(val) {
    if (val === "true" || val === "false"){
      return true
    } else {
      return false
    }
  }
isBooleanString("true") // true
isBooleanString("false") // true

isBooleanString("blabla") // false

Well for this, also have a look at org.apache.commons.lang.BooleanUtils#toBoolean(java.lang.String), along with many other useful functions.


The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.

You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.

Wrap that in a Method ContainsBoolString and you're go.

EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.

int i;
if (Int32.TryParse("Hello", out i))
  // Hello is an int and its value is in i
else
  // Hello is not an int

Benchmarks indicate they are way faster than the following:

int i;
try
{
   i = Int32.Parse("Hello");
   // Hello is an int and its value is in i
}
catch
{
   // Hello is not an int
}

Maybe there are similar methods in Java? It's been a while since I've used Java...


return value.equals("false") || value.equals("true");

See oracle docs

public static boolean parseBoolean(String s) {
        return ((s != null) && s.equalsIgnoreCase("true"));
    }

return "true".equals(value) || "false".equals(value);

Something you should also take into consideration is character casing...

Instead of:

return value.equals("false") || value.equals("true");

Do this:

return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");

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

String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;

Can also do it by regex:

Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();

Yes, but, didn't you parse "false"? If you parse "true", then they return true.

Maybe there's a misunderstanding: the methods don't test, if the String content represents a boolean value, they evaluate the String content to boolean.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas