Yes, that will lead to the same result.
To be a bit more specific:
- If
str1 isn't null, it's exactly the same, since it just passes through the ternary check to the same expression as before
- If
str1 is null, it then becomes a check to see if str2 is 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==null into an actual comparison between str1 and str2: str1==str2. Since one of the values is already null, 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 a NullPointerException, 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.