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

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

    It is never wise to call a method, be it equals() or otherwise,on a variable which may be null. That is why one usually does something like:

    if ( var != null && var.method(something) ) {
      // var.method() was true
    } else {
      // var is null or var.method is false
    }
    

    In your special case it would be sufficient to do

    if (stringVariable == null) {
    }
    

    when working with Strings it can pay to check out Apache Commons StringUtils.

    It always pays to check out the apache commons libraries as they have lots of optimized utilities (for Strings, Collections, Dates and such) which tend to be better than home-written ones.

提交回复
热议问题