Maurycy Maurycy - 8 months ago 35
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){
return true;

return false;


The usual idiom is this:

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