I want to compare two strings for equality when either or both can be null
.
So, I can’t simply call .equals()
as it can contain null
values.
The code I have tried so far :
JavaScript
x
boolean compare(String str1, String str2) {
return ((str1 == str2) || (str1 != null && str1.equals(str2)));
}
What will be the best way to check for all possible values including null
?
Advertisement
Answer
This is what Java internal code uses (on other compare
methods):
JavaScript
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}