-3

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?

FARS
  • 313
  • 6
  • 20
  • 1
    hmm .. this looks like you might be mis-using the toString - the general rule is to never-ever override it for application reasons, so generally there is no need to check its return value. There are odd corner cases, though :) – kleopatra Dec 01 '21 at 12:35

1 Answers1

2

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.
K450
  • 691
  • 5
  • 17
djsumdog
  • 2,560
  • 1
  • 29
  • 55