Understanding the Differences and Proper Use of @NotNull, @NotBlank, and @NotEmpty
The article explains how @NotNull, @NotBlank, and @NotEmpty annotations from javax.validation differ in their constraints on primitive types, strings, collections, and maps, and shows why adding @Validated to method parameters is required for the validations to take effect.
When using Bean Validation, the author discovered that validations were being skipped, prompting a review of the @NotNull usage and leading to a clarification of the differences among @NotNull, @NotBlank, and @NotEmpty.
The three annotations belong to the javax.validation.constraints package. They allow developers to replace repetitive manual checks with declarative constraints, making the code more concise.
@NotNull
Applicable primarily to primitive wrapper types such as Long, Integer, and Double. When placed on a String, the value must not be null, but an empty string ("") is permitted.
@NotBlank
Designed for String fields. The annotated value cannot be null and, after trim(), its length must be greater than zero; therefore both null and an empty string are rejected.
@NotEmpty
Can be used on String, Collection, array, Map, and similar containers. The value must not be null and its size or length must be greater than zero.
To activate these constraints, the method parameter must also be annotated with @Validated; otherwise the annotations have no effect.
The article concludes with an invitation for readers to comment and share their experiences.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
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.
