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

前端 未结 4 1962
别那么骄傲
别那么骄傲 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:04

    The equals() method does not work with null parameter.

    The method needs to have an object or string as parameter.

    public boolean equals(Object anObject)
    

    Since null is not an object. Is null an Object?.

    Also refer to java 7 documentation which says that equals will give result if and only if the object passed is not null.

    http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)

提交回复
热议问题