For starters...the safest way to compare a String
against a potentially null
value is to put the guaranteed not-null String
first, and call .equals
on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException
is it's evaluated past country[23] == null
. If it's null
, it doesn't have a .length
property. You probably meant to call country[23] != null
instead.
The second approach only compares it against the literal string "null"
, which may or may not be true given the scope of your program. Also, if COMPLETEDDATE
itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null
. Typically though, you would want to do some logic if the object you wanted wasn't null
.
Your fourth approach is correct by accident; if COMPLETEDDATE
is actually null
, the OR
will short-circuit. It could also be true if COMPLETEDDATE
was equal to the literal "null"
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…