Constraints: Null, Empty, and Blank.

As I see there is some confusion related to validation annotations usage in Java. Let’s see a quick example of the three most confusing annotations from the Hibernate Validator.

@NotNull

public class User {

   @NotNull
   private String name;


   // ...
}
Value passedValidation result
<null>🍎 – validation failed
“”🍏 – validation passed
" "🍏 – validation passed
“Alex”🍏 – validation passed

Note: only null values are not allowed, emtpy value will pass this validation.

@NotEmpty

public class User {

   @NotEmpty
   private String name;


   // ...
}
Value passedValidation result
<null>🍎 – validation failed
“”🍎 – validation failed
" "🍏 – validation passed
“Alex”🍏 – validation passed

Note: null and empty size/length values are not allowed, values with multiple spaces will pass this validation.

@NotBlank

public class User {

   @NotBlank
   private String name;


   // ...
}
Value passedValidation result
<null>🍎 – validation failed
“”🍎 – validation failed
" "🍎 – validation failed
“Alex”🍏 – validation passed

Note: null values are not allowed and trimmed length must be greater than zero.

Title image by Matthias BΓΆckel from Pixabay