15

I was just wondering if there is a better way to do this. i feel it might be inefficient. Problem is for DB reasons i need to compare strings which can sometimes be null or not.

public static boolean compareStrings(String str1, String str2){

    if(str1 == null && str2 == null) return true;

    if(str1 != null && str2 != null){
        if(str1.equals(str2))
            return true;
    }

    return false;
}
Maurycy
  • 3,911
  • 8
  • 36
  • 44

4 Answers4

49

The usual idiom is this:

return (str1 == null ? str2 == null : str1.equals(str2));
Taymon
  • 24,950
  • 9
  • 62
  • 84
  • 22
    I would like to just add that I was doing this for android and TextUtils.equals(a, b); does exactly this – Maurycy Dec 22 '11 at 01:14
34

You say that these are potentially coming from a database. At that point, any inefficiencies around a few nullity tests are entirely insignificant compared with the cost of database queries, to be honest. I would focus on the readability.

To that end, I would start using Guava and its Objects class:

boolean equal = Objects.equal(a, b);

I would expect that to be implemented as per Taymon's code, basically - but it's nice to have it in one place.

EDIT: For Java 7+ you don't need Guava. You can just use java.util.Objects.equals(a, b).

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • As far as "readability" ... that really makes me think of `object.ReferenceEquals`, which isn't a good thing :( –  Dec 01 '11 at 05:46
  • @pst: It should make you think of the static `object.Equals` method, which is the equivalent already built-into .NET. – Jon Skeet Dec 01 '11 at 05:47
  • 15
    For anyone coming across this more recently, the same thing is now in Java 7: [Objects.equals](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals%28java.lang.Object,%20java.lang.Object%29) – Steve Chambers Dec 12 '13 at 08:58
4

If you are open to using apache Commons StringUtils then they have equals which compares two strings null-safe

Bhavana C
  • 69
  • 1
1

This code would only be inefficient if it causes a bottleneck during a normal execution of your program. The only way to know if this is the case is to run your program through a profiler. Until you do that and see for a fact that this function causes performance problems, I wouldn't worry about it.

Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
  • It might be a bit picky for me to worry about this especially without profiling. I usually dont use profilers unless I come across memory leaks. I was more or less wondering if there was a better implementation than developing a static method of my own. Thank you – Maurycy Dec 01 '11 at 05:28