Possible Duplicate:
A better way to compare Strings which could be null
I have an if condition which looks like this :
if( !str1.equals(str2) )
{
---
---
---
}
where str1 and str2 are two string objects.
There are chances that str1 might be null , so is the below code equivalent to the above, along with handling the null check?
if( !(str1==null ? str2==null : str1.equals(str2)) )
{
---
---
---
}
Thanks!
Yes, that will lead to the same result.
To be a bit more specific:
str1isn’t null, it’s exactly the same, since it just passes through the ternary check to the same expression as beforestr1is null, it then becomes a check to see ifstr2is also null.And since you have the whole ternary expression wrapped up with the
!out front, that behaves the same as before.If you wanted to be a bit more clear, you could make
str2==nullinto an actual comparison betweenstr1andstr2:str1==str2. Since one of the values is alreadynull, it doesn’t matter that it’s a referential check instead of a proper string equality check, and ends up being a bit more clear in the code (to me, anyways)As others have mentioned, however, the Apache Commons library already includes this null-safe equality capability, but it does require a rather substantial library inclusion. On the other hand, many feel that the Apache Commons functionality should be effectively considered a part of Java itself, so you can decide for yourself if you want the extra dependency.
Lastly, the functionality isn’t technically equivalent, since the default
.equals()method will throw aNullPointerException, while your equality check code won’t. If that is the behavior you were looking for (which I assume it is), then you’re fine, but it is something to be aware of.