I am passing an accountid as input from an XML file as shown, which will be parsed later and will be used in our code:
123456
I think the even shorter answer that you'll like is: StringUtils.isBlank(acct);
From the documentation: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank%28java.lang.String%29
isBlank
public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace
String s1=""; // empty string assigned to s1 , s1 has length 0, it holds a value of no length string
String s2=null; // absolutely nothing, it holds no value, you are not assigning any value to s2
so null is not the same as empty.
hope that helps!!!
No, the String.isEmpty()
method looks as following:
public boolean isEmpty() {
return this.value.length == 0;
}
as you can see it checks the length of the string so you definitely have to check if the string is null before.
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()));
}