String str = "abc";
Comparing this string variable like the following.
if(str.equals("abc")) {}
In case str
is null
, it will cause a java.lang.NullPointerException
to be thrown as obvious.
To avoid that, an additional null check may be enforced. Such as,
if(str != null && str.equals("abc")) {}
I find it plain ugly. Better could be rewritten as follows.
if("abc".equals(str)) {}
This will never throw a java.lang.NullPointerException
even though str
is null
. Besides, object equals null
is never true.
The last case however, cannot be used, when the conditional expression is inverted like so,
if(!"abc".equals(str)) {
System.out.println(str.length());
}
This will cause a java.lang.NullPointerException
inside the if
block, if str
is null
.
Can this somehow be avoided without rewriting the conditional statement like the following?
if(str != null && !"abc".equals(str)) {}
This is plain ugly and unreadable.
Although the example uses a String
object, it may be a more complex object.
System.out.println(str != null ? str.length() : 0);
– HomochromousStringUtils.isEmpty()
that makes code readable as well – Frey(str != null && !"abc".equals(str))
is ugly? – Starstarboardstr
beingnull
in the first place… – SquadronON DELETE SET NULL
), a null check is unavoidable on the JPA/ORM side. I however, excluded that part from this question. – Cacaocommons-lang
'sStringUtils.isNotEmpty(string)
method, personally. If you don't want to include the lib, you can just make your own. – Explosiveif(object1 != null && object1.equals(object2)) {...}
. (A client can supply aUser
object with optional field values ofCountry
,State
andCity
all three set tonull
inUser
. In this case, it is absolutely not the client's responsibility to fight against anull
value. It is however, the upper service layer's responsibility to adequately handle ajava.lang.NullPointerException
whenever necessary). – Cacao