Java Annotations: Your Key to Cleaner and Safer Code

Exploring Common Java Annotations

In this blog post, we will delve into several essential Java annotations used for various purposes, including validation and code organization.

@NotNull

The @NotNull annotation is used to indicate that a field or parameter must not be null. It is commonly employed in validation to ensure that a value is provided.

@NotNull String userId;

@NotBlank

The @NotBlank annotation is typically applied to String fields or parameters and is used to validate that the value is not null and not just whitespace characters.

@NotBlank String userId;

@Size

The @Size annotation allows you to specify the minimum and maximum size constraints for fields or parameters, applicable to Strings, Collections, Maps, and arrays.

@Size(max = 10) String userId

@Min and @Max

The @Min and @Max annotations are used for numeric validation. They specify the minimum and maximum values that a numeric field or parameter can have.

@Email

The @Email annotation is used to validate that a String field or parameter contains a valid email address format.

Optional<@Email String> email;
//without optional
@Email String email;

@AssertTrue and @AssertFalse

These annotations are used to validate that a boolean field or parameter is true or false, respectively.

@Positive, @Negative, @PositiveOrZero, and @NegativeOrZero

These annotations validate numeric fields or parameters to ensure they are positive, negative, or zero, depending on the specific annotation used.

@Past and @Future

The @Past annotation validates that a date field or parameter represents a date in the past, while @Future validates that it represents a date in the future.

@NotNull @Future LocalDate fromDate;

@NotNull @Past LocalDate fromDate;

@Pattern

The @Pattern annotation allows you to specify a regular expression pattern that a String field or parameter must match.

Note: It is important to use regular expressions carefully when using the @Pattern annotation to avoid over-validation or under-validation.

@Size(max = 16) @Pattern(regexp = "^[0-9]+$") @NotBlank String userId

@JsonFormat

The @JsonFormat annotation, while not a validation annotation, is often used in conjunction with validation to specify the format for date serialization and deserialization when working with JSON data.

//we can change pattern and it will work on LocalDateTime as well.
@NotNull @JsonFormat(pattern = "dd-MMM-yyyy") LocalDate fromDate;

To learn more about each annotation and see practical examples, refer to the official Java documentation and relevant libraries or frameworks' documentation.

Happy coding ❤️!