Companion code for Article 2: "Modern Java Syntax: Records, Pattern Matching, and var"
This module provides comprehensive examples of modern Java syntax features introduced since Java 8.
Records are immutable data carriers with automatic implementations.
| Feature | Description |
|---|---|
| Compact constructor | Validation without repeating parameters |
| Automatic accessors | record.name() instead of record.getName() |
| Automatic equals/hashCode | Based on all components |
| Local records | Define records inside methods |
| Generic records | Type parameters work naturally |
Files:
RecordBasics.java- Simple records, validation, nested recordsRecordAdvanced.java- Generics, interfaces, static factories, local records
Pattern matching eliminates casts and enables type-safe switching.
| Feature | Description |
|---|---|
| instanceof patterns | Bind variable in same expression |
| Switch expressions | Return values from switch |
| Switch patterns | Match types and deconstruct |
| Record patterns | Extract components in patterns |
Guards (when) |
Additional conditions in patterns |
Files:
PatternMatchingBasics.java- instanceof, switch expressions, null handlingRecordPatterns.java- Deconstruction, nesting, guards, exhaustiveness
The var keyword reduces redundancy without sacrificing type safety.
| Use Case | Recommendation |
|---|---|
| Complex generics | Highly recommended |
| Constructor calls | Recommended |
| For-each loops | Recommended |
| Method returns | Use when type is obvious |
| Numeric literals | Avoid (ambiguous) |
Files:
LocalVariableTypeInference.java- Best practices, limitations, examples
Multi-line string literals without concatenation or excessive escaping.
| Feature | Description |
|---|---|
| Multi-line | No \n concatenation needed |
| Indentation | Relative to closing """ |
| No quote escaping | " works without \" |
\s |
Preserve trailing whitespace |
\ at line end |
Suppress newline |
Files:
TextBlocks.java- SQL, JSON, regex, code generation examples
# Run all examples in this module
./gradlew :02-modern-syntax:run
# Or run specific classes
./gradlew :02-modern-syntax:run --args="records.RecordBasics"| JEP | Feature | Java Version |
|---|---|---|
| JEP 286 | Local Variable Type Inference (var) |
Java 10 |
| JEP 361 | Switch Expressions | Java 14 |
| JEP 378 | Text Blocks | Java 15 |
| JEP 394 | Pattern Matching for instanceof | Java 16 |
| JEP 395 | Records | Java 16 |
| JEP 409 | Sealed Classes | Java 17 |
| JEP 440 | Record Patterns | Java 21 |
| JEP 441 | Pattern Matching for switch | Java 21 |
// Record with validation
record Customer(String id, String name) {
public Customer {
Objects.requireNonNull(id);
}
}
// Pattern matching with guards
String describe(Object obj) {
return switch (obj) {
case String s when s.length() > 10 -> "Long string";
case String s -> "Short string: " + s;
case Integer i when i > 0 -> "Positive: " + i;
case null -> "null";
default -> "Unknown";
};
}
// Record deconstruction
double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rectangle(double w, double h) -> w * h;
};
}
// var with complex generics
var grouped = items.stream()
.collect(Collectors.groupingBy(Item::category));
// Text block
String json = """
{"name": "%s", "age": %d}
""".formatted(name, age);After mastering modern syntax, proceed to:
- Module 03 - Data-Oriented Programming (applying these features to domain modeling)
- Module 04 - Functional Patterns (combining with lambdas and streams)