Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Module 02: Modern Java Syntax

Companion code for Article 2: "Modern Java Syntax: Records, Pattern Matching, and var"

Overview

This module provides comprehensive examples of modern Java syntax features introduced since Java 8.

Features Covered

1. Records (records/)

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 records
  • RecordAdvanced.java - Generics, interfaces, static factories, local records

2. Pattern Matching (patterns/)

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 handling
  • RecordPatterns.java - Deconstruction, nesting, guards, exhaustiveness

3. Local Variable Type Inference (var/)

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

4. Text Blocks (textblocks/)

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

Running the Examples

# Run all examples in this module
./gradlew :02-modern-syntax:run

# Or run specific classes
./gradlew :02-modern-syntax:run --args="records.RecordBasics"

JEPs Referenced

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

Quick Reference

// 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);

Next Steps

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)