Intellipaat 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

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...