Search code examples
javaif-statementnullpointerexception

Using equals() in if statement to check for nullability


I have an if statement which is returning a NullPointerException.

Object obj;
if (obj.toString().equals("string"))

The expected result is a NullPointerException as obj has no value assigned to it, and it's being compared to a String.

Now considering the condition below

Object obj;
if (obj.toString().equals(null))

obj still being null (as I haven't assigned a value to it), although shouldn't my if statement return as true since obj is being compared to null?


Solution

  • You need to explicitly check against the literal value null. In the following example, if the non-null check fails, it wont' run the statement after the &&; the first check short-circuits the rest of the expression

    Object obj;
    if (obj != null && obj.toString().equals("string")) { 
      //do something 
    }
    else { 
      //do another something 
    }
    

    Note:

    • null is a literal value (similar to true and false). So you should not be comparing it like a String.