Why @NotEmpty Misses Blank Strings and How @NotBlank Fixes It
The article explains why using @NotEmpty fails to detect blank strings, demonstrates the issue with a simple demo, shows the correct use of StringUtils.isBlank, and clarifies the differences between @NotNull, @NotEmpty, and @NotBlank annotations in Java validation.
Introduction
A bug was reported where a source field passed as an empty string could still be updated successfully, prompting a suggestion to add validation.
@NotEmpty(message = "source must not be empty")
private String source;The @NotEmpty annotation appears to behave like StringUtils.isEmpty, but examining the source reveals it is used incorrectly.
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}When a blank string (length > 0) is passed, @NotEmpty cannot detect the problem.
1. Reproduce Demo
String source = " ";
System.out.println(StringUtils.isEmpty(source));
System.out.println(source.length()); false
2Because isEmpty checks that the value is not null and that its length is greater than 0; a blank string has length > 0, so the method returns false.
2. Correct Validation
To validate blank strings correctly, use StringUtils.isBlank, which checks for null, empty, or whitespace‑only strings.
String source = " ";
System.out.println(StringUtils.isBlank(source)); trueThe source code of isBlank is:
public static boolean isBlank(CharSequence cs) {
int strLen = length(cs);
if (strLen == 0) {
return true;
} else {
for (int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
}Note the use of Character.isWhitespace to detect whitespace characters.
3. Differences Among @NotNull, @NotEmpty, and @NotBlank
@NotNull : the value cannot be null, but empty strings or empty collections are allowed.
@NotEmpty : the value cannot be null; empty strings are allowed only if the length is greater than 0 (i.e., the string must contain at least one character).
@NotBlank : the value cannot be null and cannot be a blank string (null, empty, or whitespace‑only).
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
