Skip to content
Advertisement

Compare two objects in Java with possible null values

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 :

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):

public static boolean compare(String str1, String str2) {
    return (str1 == null ? str2 == null : str1.equals(str2));
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement