Apply modern Java best practices (JDK 8–25) when writing, reviewing, refactoring, or migrating code. Covers step-by-step workflows for language features (records, sealed classes, pattern matching, virtual threads), Spring Boot integration, testing with JUnit 5, exception handling, DTO design, and JDK migration playbooks (8→11→17→21→25). DO NOT use for non-Java languages, Android SDK, or beginner tutorials.
90+ modern Java patterns (JDK 8–25) with architectural best practices for enterprise applications.
Determine the usage mode:
Features an LLM may not apply correctly without guidance:
// Primitive type patterns in switch (JDK 25) — new, not widely known
String classify(Object obj) {
return switch (obj) {
case int i when i > 0 -> "positive int";
case double d -> "double: " + d;
case String s -> "string: " + s;
default -> "other";
};
}
// Flexible constructor bodies (JDK 25) — statements BEFORE super()
public class ValidatedUser extends BaseEntity {
public ValidatedUser(String name, String email) {
var normalized = email.toLowerCase().trim(); // allowed before super() in JDK 25
super(name);
this.normalizedEmail = normalized;
}
}
// Stream gatherers — custom intermediate operations (JDK 25)
var windows = List.of(1, 2, 3, 4, 5).stream()
.gather(Gatherers.windowSliding(3))
.toList(); // [[1,2,3], [2,3,4], [3,4,5]]
// Virtual thread pinning — replace synchronized with ReentrantLock for I/O
// ❌ synchronized blocks pin virtual threads to carrier threads
// ✅ Use ReentrantLock instead for any synchronized block containing I/O
private final ReentrantLock lock = new ReentrantLock();
lock.lock();
try { var r = httpClient.send(req, handler); } finally { lock.unlock(); }
var for clear local typesList.of(), Map.of(), Stream.toList())shouldCalculateTotalWhenMultipleItems@Valid and validation annotationsRuntimeException; wrap checked exceptions from libraries@RestControllerAdvice for global handling; build a self-explanatory exception hierarchycatch (Exception e)Optional<T> for expected absence; reserve exceptions for truly exceptional conditionsorElseThrow() over get(); use chaining methods (or, ifPresentOrElse)--enable-preview)Match the user's request to the appropriate reference file:
| Domain | Triggers | Reference |
|---|---|---|
| Language features | Records, pattern matching, var, sealed classes, switch expressions, text blocks, primitive patterns | language.md (18 patterns) |
| Collections | List.of, Map.of, immutability, sequenced collections | collections.md (9 patterns) |
| Streams/Optional | Collection processing, null safety, Predicate.not, gatherers | streams.md (11 patterns) |
| Concurrency | Virtual threads, async, structured concurrency, scoped values | concurrency.md (10 patterns) |
| I/O/Networking | HTTP client, files, Path.of, try-with-resources | io.md (9 patterns) |
| Strings | Text blocks, formatting, isBlank, strip, repeat | strings.md (8 patterns) |
| Error handling | Exceptions, Optional, NPE, multi-catch | errors.md (7 patterns) |
| Date/time | Temporal operations, Duration, formatting | datetime.md (6 patterns) |
| Security | Crypto, random, TLS, PEM | security.md (5 patterns) |
Each pattern reference shows old vs. modern approach with minimum JDK version. Always note the JDK version requirement when suggesting modern features.
After modifying code, verify the build: mvn clean install (Maven) or ./gradlew build (Gradle).
| Tooling | Execution, profiling, jshell, JFR | tooling.md (7 patterns) |
| Testing/TDD | JUnit 5, Mockito, AssertJ, TestContainers, AAA pattern, parameterized tests, test builders | testing.md |
| DTOs/APIs | REST request/response design | dto-patterns.md |
| Exception strategy | Exception hierarchies, @ControllerAdvice, Result objects | exception-handling.md |
| Code quality | Naming, bug patterns, code smells, pitfalls, review checklist | code-quality.md |
| Migration | JDK upgrades (8→11→17→21→25), API replacements, build modernization, JPMS | migration-guide.md |
| Spring Boot | Constructor DI, @Transactional, @ConfigurationProperties, virtual threads, actuator, full REST API example | spring-boot.md |