Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java handling of Boolean and NULL

Tags:

java

boolean

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

like image 948
Maulik Shah Avatar asked Dec 10 '22 21:12

Maulik Shah


1 Answers

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.

like image 150
Pramod Karandikar Avatar answered Dec 27 '22 07:12

Pramod Karandikar