I am aware that it is better to call the equals
method over using the ==
operator (see this question). I want two strings to compare as equal if they are both null or if they represent the same string. Unfortunately the equals
method will throw an NPE
if the strings are null
. My code is currently:
boolean equals(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
}
This is inelegant. What is the correct way to perform this test?