Java 21 Modern Features

Introduction

You installed JDK 21 LTS in chapters 2–4. This chapter highlights features used across this tutorial—enough to read and try, not a full language spec. Topics: record, switch enhancements, and virtual threads (building on Multithreading).

Prerequisites

1) record — Compact Data Carriers

You met record in Ranking Game and Streams.

java
public record Student(String name, int score) {}

Compiler generates:

  • constructor, accessors (name(), score())
  • equals, hashCode, toString
java
Student s = new Student("Emma", 95);
System.out.println(s.name());

Records are immutable by convention (fields final). Use classes when you need mutable state or complex hierarchies.

2) switch Pattern Matching

Modern switch as expression with ->:

java
String type = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Unknown";
};

switch on types (pattern matching)

java
static String describe(Object value) {
    return switch (value) {
        case Integer i -> "Integer: " + i;
        case String s -> "String: " + s;
        case null -> "null value";
        default -> "Other: " + value;
    };
}

Works with Enums for exhaustive-style branches when combined with care.

3) Text Blocks (Multi-line Strings)

Java 15+ text blocks—used in Strings:

java
String json = """
        {
          "name": "Emma",
          "score": 95
        }
        """;

4) Virtual Threads (Project Loom)

Platform threads map to OS threads (traditional Thread).
Virtual threads are cheap—ideal for many blocking I/O tasks.

java
import java.util.concurrent.Executors;
 
public class VirtualThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10_000; i++) {
                int id = i;
                executor.submit(() -> {
                    System.out.println("Task " + id + " on " + Thread.currentThread());
                });
            }
        }
    }
}

Use virtual threads when workloads wait on network/disk—not for CPU-heavy parallel compute (use parallel streams or dedicated pools thoughtfully).

Tip

JDK 21 Alignment

Tutorial examples assume Java 21. In Maven / Gradle, set release/source to 21 to use these features consistently.

5) Sequenced Collections (Awareness)

Java 21 adds sequenced collection interfaces with getFirst / getLast on lists—API polish for ordered data. Explore when you use Collections heavily.

What’s Next

Regular Expressions and engineering chapters.

FAQ

Must I use records everywhere?

No. Use for DTOs and small immutable data; use classes for rich behavior.

Are virtual threads always faster?

Not for CPU-bound work. They shine with many concurrent blocking operations.

Do I need to migrate old switch syntax?

Classic switch still works; expression form is optional and clearer.

How does this relate to Android?

Android toolchain may target different Java versions—check project requirements separately from this desktop/server-focused tutorial.

Where is full JDK 21 feature list?

See Oracle Java 21 release notes.