0 votes
1 view
in Java by (10.2k points)

I want to compare two strings for equality in Java, when either or both could be null, so I cannot simply call .equals(). What is the best way?

boolean compare(String str1, String str2) {

    ...

}

return ((str1 == str2) || (str1 != null && str1.equals(str2)));

1 Answer

0 votes
by (46.1k points)

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

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...