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.

Coder Trainee
Coder Trainee
Coder Trainee
Understanding the Differences and Proper Use of @NotNull, @NotBlank, and @NotEmpty

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpringBean Validationvalidationannotations
Coder Trainee
Written by

Coder Trainee

Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.