...
- Writing Robust Java Code
Sep. 5, 2006
What is the best way to check if a Java String object is empty?
Solution 1:
Code Block |
---|
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:
Code Block |
---|
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:
Code Block |
---|
"".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.