A better way to compare Strings which could be null

The usual idiom is this:

return (str1 == null ? str2 == null : str1.equals(str2));

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.


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


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

Tags:

Java

String