Inefficient Empty String Test
ID |
java.inefficient_empty_string_test |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
code-style |
Description
Reports two idioms commonly used to test whether a String is empty and that are both clearer and marginally faster when replaced by String.isEmpty():
-
s.equals("") -
s.length() == 0(and its symmetric form0 == s.length())
Rationale
-
s.equals("")goes through the genericequals(Object)contract: a null check on the argument, a type check, and a loop body that always exits on the empty-string fast path. It also encourages the reader to consider null-safety for the wrong side of the comparison. -
s.length() == 0reads the string’scountfield via a method call and then does an integer compare. It is slightly noisier and expresses intent indirectly.
String.isEmpty() is a single-line, branchless check that reads exactly "is this string empty?" at the call site.
// Bad
if (s.equals("")) { ... }
if (s.length() == 0) { ... }
// Good
if (s.isEmpty()) { ... }
Remediation
Use String.isEmpty(). If the input may be null, combine with an explicit null check:
if (s != null && s.isEmpty()) { ... }
For the null-safe check "is this string null or empty?" prefer a small helper (for example Strings.hasText(s) already used in this codebase) instead of "".equals(s). The null-safe constant-on-the-left idiom (e.g. "foo".equals(s)) used to compare against a non-empty constant is fine and not flagged by this rule.