Why is a Boolean null object giving me an exception from a null pointer, but String does not give me NPE when compared using the == operator

Why Booleandoes comparing a null variable give me NPEusing an operator ==, but the same operator in a null variable Stringdoes not NPE.

Snippet:

public static Boolean disableDownloadOnShareURL = null; 
public static String hi= null;

public static void main(String[] args) 
{
    try
    {
        if(disableDownloadOnShareURL == true)
            System.out.println("Boolean Comparison True");
        else
            System.out.println("Boolean Comparison False");
    }
    catch(NullPointerException ex)
    {
        System.out.println("Null Pointer Exception got while comparing Boolean values");
    }

    try
    {
        if(hi == "true")
            System.out.println("String Comparison True");
        else
            System.out.println("String Comparison False");
    }
    catch(NullPointerException ex)
    {
        System.out.println("Null Pointer Exception got while comparing String values");
    }
}

Output:

Null Pointer Exception got while comparing Boolean values
String Comparison False
+4
source share
1 answer

Since in the case of Booleans comparing with logical, the VM tries to unpack the variable (i.e., tries to make the logical value logical). If this object is zero, you get NPE. Nothing of the kind is done in String, so you are not getting NPE.

+3
source

Source: https://habr.com/ru/post/1619881/


All Articles