Mastering Java 21: Key Features, Enhancements, and Code Examples

Java 21: Key Features, Enhancements, and Code Examples

Java 21, released in September 2023, is a Long-Term Support (LTS) release and comes with major improvements that make Java more expressive, scalable, and developer-friendly.

Let’s dive into the top features of Java 21 with code examples and use cases.


๐Ÿš€ 1. Virtual Threads (Project Loom)

Problem: Traditional threads are expensive and limited in scalability.

Solution: Virtual threads are lightweight threads that improve concurrency performance and reduce the overhead of using many threads.

public class VirtualThreadDemo {
    public static void main(String[] args) {
        Runnable task = () -> System.out.println("Running in " + Thread.currentThread());
        
        // Launching 1 million virtual threads
        for (int i = 0; i < 1000000; i++) {
            Thread.startVirtualThread(task);
        }
    }
}
Note: Virtual threads use the same API as platform threads but are scheduled by the JVM and not tied to OS threads.

๐ŸŽฏ 2. Pattern Matching for switch (Finalized)

This allows matching object types in switch expressions and performing specific actions based on type.

static String formatter(Object obj) {
    return switch (obj) {
        case Integer i -> "Integer: " + i;
        case String s  -> "String: " + s.toUpperCase();
        case null      -> "Null value";
        default        -> "Unknown type";
    };
}
Why it matters: Cleaner and more readable type-specific logic.

๐Ÿ“ฆ 3. Record Patterns (Finalized)

Allows destructuring records directly in pattern matching expressions.

record Person(String name, int age) {}

static void printInfo(Object obj) {
    if (obj instanceof Person(String name, int age)) {
        System.out.println(name + " is " + age + " years old.");
    }
}
Use case: Simplifies working with data records by extracting values directly.

๐Ÿ’ฌ 4. String Templates (Preview)

Provides cleaner and safer string interpolation using templates.

import static java.util.FormatProcessor.FMT;

String name = "Java";
String message = FMT."Hello, \{name}!";
System.out.println(message);
Note: This is a preview feature and must be enabled using --enable-preview.

⏲ 5. Sequenced Collections

Java 21 adds a new interface SequencedCollection with methods like reversed(), getFirst(), getLast().

List<String> list = List.of("A", "B", "C");
System.out.println(list.reversed()); // [C, B, A]
Why it matters: Uniform access to elements from both ends in lists, sets, and maps.

๐Ÿ” 6. Unnamed Patterns & Variables (Preview)

Simplify pattern matching where you don’t need to name all variables.

if (obj instanceof Person(String _, int age)) {
    System.out.println("Age is " + age);
}
Benefit: Cleaner, intention-revealing code without unused variables.

๐Ÿ•น 7. Scoped Values (Incubator)

A safer and faster alternative to ThreadLocal for sharing values between methods in the same thread (including virtual threads).

ScopedValue<String> USER_ID = ScopedValue.newInstance();

ScopedValue.where(USER_ID, "abc123").run(() -> {
    System.out.println(USER_ID.get());
});

๐ŸŒ 8. Deprecations and Removals

  • Final removal of the Security Manager.
  • Some internal APIs moved/removed—clean up old libraries.

๐Ÿ“… 9. New DateTime Parsing Enhancements

Improved parsing in java.time.format with better error messages and corner-case handling.


⚙️ How to Enable Preview Features

To test preview features like string templates, use:

javac --enable-preview --release 21 MyApp.java
java --enable-preview MyApp

๐Ÿง  Final Thoughts

  • Java 21 is a significant LTS release—upgrade if you haven’t!
  • Virtual threads are a game-changer for high-concurrency applications.
  • Pattern matching and record patterns boost developer productivity.
  • New collection and language enhancements bring Java closer to modern languages like Kotlin and Scala.

๐Ÿ†• Continue Learning After Java 21 Features

Java 21 introduces modern language constructs and concurrency improvements that shape today’s Java ecosystem. Strengthen your understanding with interview preparation, advanced concurrency, and real-world Java usage.

๐Ÿ’ผ Java 21 Interview Questions

Practice commonly asked interview questions based on Java 21 features and real-world scenarios.

๐Ÿ•— Java 8 Interview Questions

Revisit Streams, Lambdas, and functional programming concepts that Java 21 builds upon.

⚙️ Java Multithreading Interview Questions

Strengthen thread fundamentals before moving to virtual threads and structured concurrency.

๐Ÿš€ Java 25 New Features & Migration Guide

Learn what’s new in Java 25 and how to safely migrate from Java 21 in real projects.

๐Ÿง  Java 25 Interview Questions & Answers

Prepare for senior-level interviews covering JVM internals, performance, and modern Java.

๐Ÿงต Java 25 Concurrency (Advanced)

Deep dive into structured concurrency, virtual threads, and scalability trade-offs.

๐Ÿงฉ Structured Concurrency – Complete Guide

Understand structured concurrency concepts introduced after Java 21 and matured in Java 25.

๐Ÿ—️ Java System Design Interview Questions

Learn how Java 21+ features influence scalability, throughput, and architecture decisions.

๐Ÿงช Advanced Java Programs (Real-World)

Apply Java 21 features in production-style, performance-oriented coding scenarios.