Java Notes
HubWhat Is Java?History of JavaFeatures of JavaJava EditionsJDK, JRE, and JVMYour First Java ProgramJava Program StructureJava Compilation ProcessIdentifiers in JavaKeywords in JavaVariables in JavaData Types in JavaType Casting in JavaOperators in JavaInput and Output in JavaComments in JavaIf-Else Statements in JavaSwitch-Case in JavaFor Loop in JavaWhile Loop in JavaDo-While Loop in JavaNested Loops in Javabreak and continue in JavaArray IntroductionOne Dimensional ArrayMulti Dimensional ArrayJagged Array in JavaArray OperationsArray Programs — FundamentalsArray Interview QuestionsString Class in JavaImmutable Strings in JavaString MethodsStringBuilder in JavaStringBuffer in JavaString Programs — FundamentalsString Interview QuestionsOOPs IntroductionClass and Object in JavaConstructor in Javathis Keyword in Javastatic Keyword in JavaEncapsulation in JavaInheritance in Javasuper Keyword in JavaPolymorphism in JavaMethod Overloading in JavaMethod Overriding in JavaAbstraction in JavaAbstract Class in JavaInterface in JavaObject Class in JavaWrapper Class in JavaInner Class in JavaAnonymous Class in JavaObject Cloning in JavaJava Collections Framework OverviewGenerics in JavaArrayList in JavaLinkedList in JavaVector in JavaStack in JavaHashSet in JavaLinkedHashSet in JavaTreeSet in JavaPriorityQueue in JavaArrayDeque in JavaDeque Interface in JavaHashMap in JavaLinkedHashMap in JavaTreeMap in JavaHashtable in JavaIterator in JavaComparable vs Comparator in JavaJava Collections Practice ProgramsException Handling IntroductionException Hierarchy in JavaTry-Catch Block in JavaFinally Block in Javathrow and throws Keywords in JavaCustom Exceptions in JavaException Handling Best PracticesFile Class in JavaByte Streams in JavaCharacter Streams in JavaBuffered Streams in JavaSerialization in JavaDeserialization in JavaJava NIO PackageLambda Expression in Java 8Functional Interface in Java 8Method Reference in Java 8Default and Static Methods in InterfacesStream API in Java 8Optional Class in Java 8Date and Time API in Java 8Thread IntroductionThread Life Cycle in JavaThread Class in JavaRunnable Interface in JavaCreating Threads in JavaThread Priority in JavaDaemon Threads in JavaSynchronization in JavaInter-Thread Communication in JavaExecutor Framework in JavaMultithreading Programs in JavaJDBC IntroductionJDBC ArchitectureMySQL Connection with JDBCStatement Interface in JDBCPreparedStatement in JDBCResultSet in JDBCCallableStatement in JDBCTransaction Management in JDBCBatch Processing in JDBCJDBC ProjectsServlet IntroductionGenericServletHttpServletServlet Life CycleRequest and Response ObjectsCookies in ServletsSession TrackingJSP IntroductionJSP Tags and JSTLExpression Language (EL)MVC ArchitectureSpring Framework IntroductionSpring Core ContainerSpring BeansDependency InjectionSpring Boot IntroductionREST API with Spring BootValidation in Spring BootCRUD ApplicationSpring Data JPAException Handling in Spring BootSpring SecurityJWT Authentication — Java ProgrammingConfig ServerEureka Server - Service DiscoveryAPI GatewayDocker DeploymentTime ComplexityRecursion in JavaLinked List in JavaStack in Java — DSA in JavaQueue in JavaHashing in JavaSorting Algorithms in JavaSearching Algorithms in JavaTree Data Structure in JavaHeap (DSA)Graph Data Structure in JavaDynamic Programming in JavaSingleton Design PatternFactory Design PatternBuilder Design PatternAdapter Design PatternObserver Design PatternMVC Pattern — Java ProgrammingBasic Java ProgramsArray Programs — PracticeString Programs — PracticeOOP ProgramsCollection ProgramsMultithreading ProgramsJDBC ProgramsPlacement Coding QuestionsStudent Management System — Java ProgrammingEmployee Management SystemLibrary Management System — Java ProgrammingBanking System — Java ProgrammingChat ApplicationE-Commerce BackendSpring Boot Fullstack ProjectCore Java Interview QuestionsOOPs Interview QuestionsCollections Interview QuestionsMultithreading Interview QuestionsJDBC Interview QuestionsSpring Framework Interview QuestionsCoding Interview QuestionsJava Cheat SheetQuick Revision Notes — Java ProgrammingImportant Java ProgramsImportant Formulas & ConceptsJava Master Course - Learning Roadmap
Complete guide to input validation in Spring Boot - Jakarta Bean Validation, custom validators, group validation, and validation error handling.
Setup
xml example
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>Validation Annotations Reference
| Annotation | Applies To | Description |
|---|---|---|
@NotNull | Any | Must not be null |
@NotBlank | String | Not null, not empty, not whitespace |
@NotEmpty | String/Collection | Not null and not empty |
@Size(min, max) | String/Collection | Length/size bounds |
@Min(value) | Number | Minimum value |
@Max(value) | Number | Maximum value |
@Positive | Number | > 0 |
@PositiveOrZero | Number | >= 0 |
@Negative | Number | < 0 |
@Email | String | Valid email format |
@Pattern(regexp) | String | Matches regex |
@Past | Date/Time | Must be in past |
@Future | Date/Time | Must be in future |
@Digits(integer, fraction) | Number | Digit constraints |
@DecimalMin | Number | Minimum decimal value |
@DecimalMax | Number | Maximum decimal value |
Applying Validation in Controller
java example
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public ResponseEntity<?> createUser(@RequestBody @Valid UserRegistrationRequest request) {
// If validation fails, MethodArgumentNotValidException is thrown
// before this code executes
User user = userService.register(request);
return ResponseEntity.status(HttpStatus.CREATED).body(user);
}
// Validate path variable
@GetMapping("/{id}")
public ResponseEntity<?> getUser(@PathVariable @Min(1) Long id) {
return ResponseEntity.ok(userService.getById(id));
}
// Validate request params
@GetMapping
public ResponseEntity<?> searchUsers(
@RequestParam @NotBlank String query,
@RequestParam @Min(0) int page,
@RequestParam @Min(1) @Max(100) int size) {
return ResponseEntity.ok(userService.search(query, page, size));
}
}Important: Add @Validated on the class for path variable / request param validation:java example
@RestController
@Validated // Required for method-level validation
@RequestMapping("/api/users")
public class UserController { }Custom Validator
Step 1: Create Annotation
java example
@Documented
@Constraint(validatedBy = UniqueEmailValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface UniqueEmail {
String message() default "Email already registered";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}Step 2: Create Validator Class
java example
@Component
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
@Autowired
private UserRepository userRepository;
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
if (email == null) return true; // Let @NotNull handle null check
return !userRepository.existsByEmail(email);
}
}Step 3: Use It
java example
@Data
public class UserRequest {
@NotBlank
@Email
@UniqueEmail // Custom validation!
private String email;
}Cross-Field Validation
java example
// Class-level validator
@Documented
@Constraint(validatedBy = PasswordMatchValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PasswordMatch {
String message() default "Passwords do not match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, Object> {
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
if (obj instanceof ChangePasswordRequest req) {
return req.getNewPassword().equals(req.getConfirmPassword());
}
return true;
}
}
@Data
@PasswordMatch
public class ChangePasswordRequest {
@NotBlank
private String currentPassword;
@NotBlank @Size(min = 8)
private String newPassword;
@NotBlank
private String confirmPassword;
}Nested Object Validation
Example
@Data
public class OrderRequest {
@NotBlank
private String customerName;
@Valid // Triggers validation on nested object!
@NotNull
private AddressDTO shippingAddress;
@Valid
@NotEmpty
private List<OrderItemDTO> items;
}
@Data
public class AddressDTO {
@NotBlank private String street;
@NotBlank private String city;
@NotBlank @Pattern(regexp = "^[0-9]{6}$") private String pincode;
}
@Data
public class OrderItemDTO {
@NotNull @Positive private Long productId;
@NotNull @Min(1) private Integer quantity;
}
Handling Validation Errors
java example
@RestControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationErrors(
MethodArgumentNotValidException ex) {
Map<String, String> fieldErrors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
fieldErrors.put(error.getField(), error.getDefaultMessage()));
Map<String, Object> response = new LinkedHashMap<>();
response.put("success", false);
response.put("message", "Validation failed");
response.put("errors", fieldErrors);
response.put("timestamp", LocalDateTime.now());
return ResponseEntity.badRequest().body(response);
}
// For @Validated on path/query params
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Map<String, Object>> handleConstraintViolation(
ConstraintViolationException ex) {
Map<String, String> errors = new HashMap<>();
ex.getConstraintViolations().forEach(v ->
errors.put(v.getPropertyPath().toString(), v.getMessage()));
Map<String, Object> response = Map.of(
"success", false,
"message", "Constraint violation",
"errors", errors
);
return ResponseEntity.badRequest().body(response);
}
}Interview Key Points
@Validon@RequestBodytriggers validation before controller method runs@Validatedon class enables method-level validation (params, path vars)- Custom validators implement
ConstraintValidator<Annotation, Type> - Use
@Validon nested objects to trigger their validation - Validation errors throw
MethodArgumentNotValidException @NotNullvs@NotBlankvs@NotEmpty: Null → Empty → Whitespace- Custom class-level annotations enable cross-field validation
- Always return field-specific error messages for good UX
Summary
In this chapter, we learned about Validation in Spring Boot in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Continue the lesson path
Study next in this module
01Spring FrameworkCRUD ApplicationBuild a complete CRUD application with Spring Boot - project setup, layered architecture, full CRUD operations, testing, and deployment.02Spring FrameworkREST API with Spring BootBuilding RESTful APIs with Spring Boot - REST principles, controller annotations, request/response handling, pagination, HATEOAS, and API versioning.03Spring FrameworkSpring Boot IntroductionComplete introduction to Spring Boot - auto-configuration, starter dependencies, embedded servers, creating your first Spring Boot application, and project structure.04Spring FrameworkSpring Data JPAComplete guide to Spring Data JPA - entity mapping, repository interfaces, query methods, JPQL, native queries, relationships, and database operations.