@NotNull: The CharSequence, Collection, Map or Array object is not null, but can be empty.
@NotEmpty: The CharSequence, Collection, Map or Array object is not null and size > 0.
@NotBlank: The string is not null and the trimmed length is greater than zero.
To help you understand, let’s look into how these constraints are defined and carried out (I’m using version 4.1):
-
The
@NotNullconstraint is defined as:@Constraint(validatedBy = {NotNullValidator.class})This class has an
isValidmethod defined as:public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { return object != null; } -
The
@NotEmptyconstraint is defined as:@NotNull @Size(min = 1)So this constraint uses the
@NotNullconstraint above, and@Sizewhose definition differs based on the object but should be self explanitory. -
Finally, the
@NotBlankconstraint is defined as:@NotNull @Constraint(validatedBy = {NotBlankValidator.class})So this constraint also uses the
@NotNullconstraint, but also constrains with the NotBlankValidator class. This class has anisValidmethod defined as:if ( charSequence == null ) { //curious return true; } return charSequence.toString().trim().length() > 0;Interestingly, this method returns true if the string is null, but false if and only if the length of the trimmed string is 0. It’s ok that it returns true if it’s null because, as I mentioned, the
@NotEmptydefinition also requires@NotNull.
Here are a few examples:
-
String name = null;
@NotNull: false
@NotEmpty: false
@NotBlank: false -
String name = “”;
@NotNull: true
@NotEmpty: false
@NotBlank: false -
String name = ” “;
@NotNull: true
@NotEmpty: true
@NotBlank: false -
String name = “Great answer!”;
@NotNull: true
@NotEmpty: true
@NotBlank: true