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
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") ) {
...