5

Boolean object in JAVA can have 3 values True, False, NULL

public class First {

    public static void main(String args[])
    {
        System.out.println("equals(new Boolean(\"True\"),True) :: " + isEqual(new Boolean("True"), true));
        System.out.println("equals(new Boolean(\"False\"), new Boolean(null)) :: " + isEqual(new Boolean("False"), new Boolean(null)));
        System.out.println("equals(new Boolean(\"False\"), null)) :: " + isEqual(new Boolean("False"), null));
    }

    static boolean isEqual(Boolean a, Boolean b)
    {
        return a.equals(b);
    }
}

Output for above code is

equals(new Boolean("True"),True) :: true
equals(new Boolean("False"), new Boolean(null)) :: true
equals(new Boolean("False"), null)) :: false

Please explain why Case 2 returns true but Case 3 returns false

3
  • Obviously null cannot be equal to any valid, non-null reference. Commented Aug 4, 2015 at 9:41
  • How can be null equal to any other value ? and in second you are creating object new Boolean(null) Commented Aug 4, 2015 at 9:42
  • 1
    new Boolean(null) means a Boolean object created and its value is false. Commented Aug 4, 2015 at 9:46

2 Answers 2

9

That's because the constructor for Boolean, if provided with null will allocate a Boolean object representing the value false

Read here: http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html

public Boolean(String s)

Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false. Examples: new Boolean("True") produces a Boolean object that represents true. new Boolean("yes") produces a Boolean object that represents false. Parameters:s - the string to be converted to a Boolean.

Sign up to request clarification or add additional context in comments.

Comments

4

If you look at the source code of Booleanclass, you can se that passing a nullvalue returns false:

private static boolean toBoolean(String name) { 
    return ((name != null) && name.equalsIgnoreCase("true"));
 }

1 Comment

I don't know what version you were using then but in 1.8 there is public static boolean parseBoolean(String s) { return ((s != null) && s.equalsIgnoreCase("true")); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.