Maurycy Maurycy - 2 months ago 9
Java Question

A better way to compare Strings which could be null

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

Answer

The usual idiom is this:

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