-3

I have an if statement which is returning a NullPointerException.

Cause: it is comparing two objects, one of them is null:

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

How I know obj is null? If I try to print that object (System.out.println(obj.toString()), logically I get a NullPointer as well. When I click the error, instead of selecting the corresponding line to the if statement, it selects my System.out statement, indicating that the error source is my object (also, I'm veryfing whether the object returns as null from my database, which in my case, a "null" keyword takes place where the "string" is in my statement).

Taking in consideration that I do know my obj is null (even by checking that it is null in my database), it is not possible to compare it with another object, since apparently if statements are unable to compare objects when one of them is null.

I know that by checking the following code (as described above):

Object obj;
        if (obj.toString.equals(null))
           { //do something }

Shouldn't that statement return true? Cause it is not doing what is inside that if block.

Mainly, when the compiler reads if (obj.toString.equals("string")), since it is false (cause obj doesn't equal to "string") that should fall into my else block but that's not happening.


Any thoughts?


for instance, when I say that I click the error and it leds me to the if statement line (or my System.out line, for object verification), that's what I mean: enter image description here

FARS
  • 108
  • 14
  • 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
  • 586
  • 3
  • 16
djsumdog
  • 2,263
  • 1
  • 24
  • 49