Is condition str2==null always true?
1. private boolean isSameString(String str1, String str2) 2. {
3. if(str1==null && str2!=null) return false;
4. if(str2==null && str1!=null) return false;
5. if(str1==null && str2==null) return true;
6. return (str1.equals(str2));
7. }
IDE suggests that str2==null in line 5 is redundant and is always true.
Please sign in to leave a comment.
Very clever of it, and absolutely the case. Nice work on someone's part.
do you think this is a little easier to read?
private static boolean areSame(Object one, Object two){
if(one == null ^ two == null)
return false;
if(one == null && two == null)
return true;
return one.equals(two);
}
Another suggestion:
And my preferred:
Hey, that's really cool; I never thought of that. With that idea, the thing can be turned into a one-liner:
Regards,
Jens
Which, as I just realized, should definitely be turned into an intention in the ipp.
(Dave, are you reading this?)
>
+1 much better understandable than the original one
Technically:
So unless you actually want the behaviour of regarding two
strings as the same string you should return false when str1 and str2 are
.
I want the method to return true when both are null.
passing noth arguments as null, it will certainly hit line 5 and will return correct value.
but as the original question was-Is it redundant...?
Yes. After line 3, if you know that str1 is null, then str2 must be null (otherwise line 3 would have returned). The analysis to figure this out looks to be pretty darn clever.
--Dave
I've only seen this in SQL. Are there any other languages handling null like
SQL does?
IMO, someone must have been smoking something when the behaviour of
null was put into sql.
Whoever creates a logic system where (a = b or a != b) can be a false
statement may have a great head, but it's floating a little to high above
the clouds.
It may be preety for mathematic/logic investigation, but it's a fountain of
unnecessary bugs in daily use.