4

Why comparison of null Boolean variable gives me NPE using == operator but same operator on null String variable do not give 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
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
  • Possible duplicate of this one : http://stackoverflow.com/questions/11005286/check-if-null-boolean-is-true-results-in-exception – Arnaud Dec 14 '15 at 12:57

1 Answers1

4

Because in the case of Booleans comparing with booleans the VM tries to unbox the variable (i.e. trying to make a boolean out a Boolean). If this object is null, you get a NPE. On a String nothing like is done, so you don't get a NPE.

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49