Skip to end of metadata
Go to start of metadata
You are viewing an old version of this page. View the current version.
Compare with Current
View Page History
« Previous
Version 3
Next »
Java Coding Best Practices
- Java: Code Conventions for the Java Programming Language
Sep. 5, 2006
What is the best way to check is a Java String object is empty?
Solution 1:
- Pros:
- 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:
Solution 3:
- Pros:
- avoids the null pointer exception issue that Solution 1 has
- readable but awkward at first
- 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.