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;
}
2

4 Answers 4

49

The usual idiom is this:

return (str1 == null ? str2 == null : str1.equals(str2));
1
  • 22
    I would like to just add that I was doing this for android and TextUtils.equals(a, b); does exactly this
    – Maurycy
    Commented Dec 22, 2011 at 1: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).

3
  • As far as "readability" ... that really makes me think of object.ReferenceEquals, which isn't a good thing :(
    – user166390
    Commented Dec 1, 2011 at 5:46
  • @pst: It should make you think of the static object.Equals method, which is the equivalent already built-into .NET.
    – Jon Skeet
    Commented Dec 1, 2011 at 5:47
  • 15
    For anyone coming across this more recently, the same thing is now in Java 7: Objects.equals Commented Dec 12, 2013 at 8:58
4

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

0
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.

1
  • 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
    Commented Dec 1, 2011 at 5:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.