Search code examples
javaexceptionbooleantry-catch

Why is Boolean.valueOf(String) returning false when given neither true or false but a random String?


When using the method Boolean.valueOf(String) the return value is false when given any String besides "true". This try block neverseems to fail even if it should?

boolean a;

String b = "randomTextThatsNotTrueOrFalse";

try{
a= Boolean.valueOf(b);
} 
catch(IllegalArgumentException e) {

 LOG.error(b  + "is invalid. Only true or false are possible  Options.");

}

Solution

  • As per the spec (and, as expected, the source code of the OpenJDK implementation follows this spec), "true" (with any casing) is parsed as true, and all other strings are parsed as false:

       * Returns a {@code Boolean} with a value represented by the
       * specified string.  The {@code Boolean} returned represents a
       * true value if the string argument is not {@code null}
       * and is equal, ignoring case, to the string {@code "true"}.
       * Otherwise, a false value is returned, including for a null
       * argument.
    

    Reading javadoc is important; you should make a habit of it.

    If you want a method that returns true if passed "true", false if passed "false", and throws an IAEx otherwise, you'd have to write it yourself. It's about 80 characters worth of code.