Comparing strings in java
Possible Duplicate:
Better way to compare strings that may be null
I have an if condition that looks like this:
if( !str1.equals(str2) )
{
---
---
---
}
where str1 and str2 are two string objects.
Is there a chance str1 could be null, since the code below is equivalent to the above, and also handling null check?
if( !(str1==null ? str2==null : str1.equals(str2)) )
{
---
---
---
}
Thank!
source to share
Yes, it will lead to the same result.
To be more specific:
- If
str1
not null, it is exactly the same as it just goes through the ternary test to the same expression as before - If
str1
null it becomes a check to see if it isstr2
also null.
And since you have the whole triple expression wrapped up with a front !
that behaves the same as before.
If you want to be more intuitive, you can make str2==null
the actual comparison between str1
and str2
: str1==str2
. Since one of the values ββis already equal null
, it doesn't matter that it is a referential check instead of properly checking for string equality and ends up being still clearer in the code (to me, anyway)
As others have noted, the Apache Commons library already includes this zero-security capability, but it requires a fairly substantial library inclusion. On the other hand, many believe that the Apache Commons functionality should be effectively treated as part of Java itself, so you can decide for yourself if you want an additional dependency.
Finally, the functionality is not technically equivalent, as the default method .equals()
will generate NullPointerException
, while your equality checking code will not. If this is the behavior you were looking for (I suppose it is), then you are fine, but it is something to be aware of.
source to share
Assuming you want the two zeros to be equal, of course. Depending on your method, NullPointerException might be the correct answer. You can save a lot of information by reading
org.apache.commons.lang.StringUtils
!StringUtils.equals(str1, str2);
handles zeros for you in the same way.
source to share
Yes, your code will enter the block if
only if the strings are not equal (either only one of them is null, or both of them are not null and different).
Another way to do it is
if( (str1 == null && str2 != null) || !str1.equals(str2) ){
// Only executes when strings are unequal
}
It's a matter of taste, some people are allergic to triple operators. (I like them).
source to share