If Java 7+, use Objects.equals()
; its documentation explicitly specifies that:
[…] if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.
which is what you want.
If you don’t, your method can be rewritten to:
return s1 == null ? s2 == null : s1.equals(s2);
This works because the .equals()
contract guarantees that for any object o
, o.equals(null)
is always false.