Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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
0 votes
1 answer
asked Sep 19, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...