Maurycy Maurycy - 1 year ago 70
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;

Answer Source

The usual idiom is this:

return (str1 == null ? str2 == null : str1.equals(str2));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download