Can We Rely On String.isEmpty For Checking Null Condition On A String In Java?
Answer :
No, absolutely not - because if acct
is null, it won't even get to isEmpty
... it will immediately throw a NullPointerException
.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of &&
here, rather than your ||
in the previous code; also note how in your previous code, your conditions were wrong anyway - even with &&
you would only have entered the if
body if acct
was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Use StringUtils.isEmpty
instead, it will also check for null.
Examples are:
StringUtils.isEmpty(null) = true StringUtils.isEmpty("") = true StringUtils.isEmpty(" ") = false StringUtils.isEmpty("bob") = false StringUtils.isEmpty(" bob ") = false
See more on official Documentation on String Utils.
You can't use String.isEmpty()
if it is null. Best is to have your own method to check null or empty.
public static boolean isBlankOrNull(String str) { return (str == null || "".equals(str.trim())); }
Comments
Post a Comment