Why do I get a NullPointerException when comparing a String with null?

前端 未结 4 1959
别那么骄傲
别那么骄傲 2020-12-06 05:20

My code is breaking on the following line with a nullpointerexception:

 if (stringVariable.equals(null)){

Previous to this statement, I dec

4条回答
  •  借酒劲吻你
    2020-12-06 06:26

    if stringvariableis already null, it doesn't exist as a String object anymore, so it won't even have a .equals method! So in the event when stringvariable is null, what you are really doing is null.equals(null), at which point you'll get the NullPointerException because null doesn't have a .equals() method.

提交回复
热议问题