Java equals() ordering

后端 未结 6 943
执念已碎
执念已碎 2021-01-12 02:55

If I try to do a .equals() on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to

6条回答
  •  深忆病人
    2021-01-12 03:24

    What you've got is fine. It's even possible to use a String literal.

    if( "value".equals(variable) ) {
        ...
    

    If you don't like that, you can always explicitly check for null and equality, and combine the two checks with &&. The short circuiting of the operator will make sure you never get a NPE.

    if( (variable != null) && variable.equals("value") ) {
        ...
    

提交回复
热议问题