Java's parseBool doesn't really behave how I'd expect

Published May 3, 2012

Java's parseBool() doesn't really behave how I'd expect

The parseBool() method on Java's Boolean class returns false in all cases where it doesn't encounter the string "true", for example...

public class ParseBool
{
    public static void main(String[] args)
    {
    String strTrue = "true";
    String strFalse = "false";
    String strEmpty = "";
    String strNull = null;
    String str1 = "1";
    System.out.println("strTrue: " + Boolean.parseBoolean(strTrue));
    System.out.println("strFalse: " + Boolean.parseBoolean(strFalse));
    System.out.println("strEmpty: " + Boolean.parseBoolean(strEmpty));
    System.out.println("strNull: " + Boolean.parseBoolean(strNull));
    System.out.println("str1: " + Boolean.parseBoolean(str1));
    }
}

Running this code gives the output:

true: true
false: false
empty: false
null: false
1: false

The problem here is that a value of null is almost never equal to false. This is especially true in the case of user input, consider a form input "Bill the customer?"" with options yes, no or blank/no answer - obviously in a practical situation you would have validation that would force the user to select an option - but in the case that you do not, it makes no sense that blank or null maps to false, blank or null is meaning in itself, it means the field wasn't filled in, not "no, don't bill the customer".

Possible solutions

Personally I think parseBoolean should throw an Exception similar to parseInteger or parseDouble, but that's not how things are, so to get around this you can:

Check for null

(input==null) ? null : Boolean.parseBool(input);

Create your own parseBoolean

public Boolean tobysParseBool(String input)
{
    if(input == null || "".equals(input)) throw new Exception();
    return (input.equalsIgnoreCase("true")) ? true : false;
}

You could also re-write this method to favour true instead of false as above by changing the last line to:

return (input.equalsIgnoreCase("false")) ? false : true;

This way false will only be returned if the input is explicitly false, all other values will be true, though it will usually be safer to check for true and return false for all else.