What is the best way to check if a Java String object is empty
Sep. 5, 2006
What is the best way to check if a Java String object is empty?
Solution 1:
someString.equals("");
Pros:
readable
Cons:
possible null pointer exception if someString is null
create extra String object (""). Overhead can be reduced by using static final String EMPTY_STRING = "";
not very efficient because equals first does a string length comparison
Solution 2:
public boolean isNotNullAndEmpty(String str) {
if((null != str) && (str.length() == 0)) {
return true;
}
else {
return false;
}
// ... or just
// return (str == null) ? false : str.length() == 0;
}
Pros:
tests for null string
efficient
abstraction
Cons:
a bit more code to write
Solution 3:
"".equals(someString);
Pros:
avoids the null pointer exception issue that Solution 1 has
readable but awkward at first. Maybe use EMPTY_STRING.equals(someString)
Cons:
create extra String object (""). Overhead can be reduced by using static final String EMPTY_STRING = "";
not very efficient because equals first does a string length comparison
Conclusion
Either use Solution 2 or Solution 3. If you use Solution 3, make sure that you use a static final empty string.
Solution 3 is the clear winner here –
The Java compiler is (now days) very good at coalescing repeated String contants, so that overhead, listed as a Con, is negligible if not completely insignificant. The “extra String object&rdquo gets reused, as can be seen from the output of javap
It is efficient to compare lengths first – doing so avoids unnecessary character comparisons since Strings of differing length can't be
equals(), and anyway...Solution 2 requires an additional method call – it is called then it calls
str.length()so it suffers from the same alleged inefficiency as Solution 3, but adds another call level on top of that.Solution 3 gets the
!= nulltest "for free" – Solution 2 must explicity check fornull.Solution 2 requires a non-standard String subclass or a static method in a utility class.
Solution 3 is a well known idiom in the language. Yes, awkward at first but fluent developers recognize it.
Using a
static finalempty String only saves space if there's only one in the system, and then you again require a utility class as a place to keep it. Use Solution 3 exactly as it's written:"".equals(someString);