Why is this an issue?

Calling String.isEmpty() clearly communicates the code’s intention, which is to test if the string is empty. Using String.length() == 0 is less direct and makes the code less readable. This preference for isEmpty() extends to all CharSequence objects, including StringBuilder and StringBuffer.

A String.strip().length() == 0 or String.trim().length() == 0 test is a blankness check, and String.isBlank() states that intent directly.

It is also cheaper. Invoking operations that create new string objects with white space removed incurs unnecessary memory allocation and management overhead: whenever there is white space to remove, strip() and trim() copy the remaining characters into a new string, which is then discarded as soon as its length has been read. isBlank() inspects the characters in place and allocates nothing.

Exceptions

String.isBlank() is only available from Java 11 on. This rule does not raise an issue on strip().length() or trim().length() comparisons when the project targets an earlier version.

How to fix it

Code examples

Noncompliant code example

if ("string".length() == 0) { /* … */ } // Noncompliant

if ("string".length() > 0) { /* … */ } // Noncompliant
StringBuilder sb = new StringBuilder();
...
if (sb.length() == 0) { /* … */ } // Noncompliant
if ("string".strip().length() == 0) { /* … */ } // Noncompliant

if ("string".trim().length() > 0) { /* … */ } // Noncompliant

Compliant solution

if ("string".isEmpty()){ /* … */ }

if (!"string".isEmpty()){ /* … */ }
StringBuilder sb = new StringBuilder();
...
if (sb.isEmpty()) { /* … */ }
if ("string".isBlank()) { /* … */ }

if (!"string".isBlank()) { /* … */ }

Pitfalls

strip() removes exactly the characters isBlank() treats as white space, both relying on Character.isWhitespace, so strip().length() == 0 and isBlank() always agree.

trim() does not. It removes every character up to and including U+0020, which covers control characters such as U+0000 that Character.isWhitespace rejects, and it leaves Unicode white space above U+0020, such as the em space U+2003, in place. Replacing trim().length() == 0 with isBlank() therefore makes strings of Unicode white space count as blank and strings of control characters count as non-blank. The issue message and the quick fix say so explicitly; apply the fix only when that is the intended behavior, and keep trim().isEmpty() otherwise.

Resources

Documentation