July 2, 2025By

New Features in Java 21

New Features in Java 21

Java 21, released in September 2023, brings a fresh wave of enhancements to the Java platform. As a Long-Term Support (LTS) release, it promises stability, performance, and modern capabilities that both enterprise and individual developers can rely on for years to come. With every LTS version, Java becomes more powerful, and Java 21 features are no exception. Explore the New Features in Java 21*, including virtual threads, pattern matching, and performance improvements that boost productivity and modern Java development.*

The following are some Java 21 features that make this release stand out: enhancements in pattern matching, record destructuring, lightweight concurrency with virtual threads, and developer productivity through string templates and simplified syntax. Let’s explore each one in depth.


1. Pattern Matching for Switch (JEP 441)

The first of the most impactful Java 21 features is Pattern Matching for switch. This enhancement modernizes control flow in Java and eliminates the need for multiple instance of and type casts.

Why it matters:In traditional Java, you’d use verbose if-else or instanceof checks. Java now supports type patterns inside switch cases thanks to pattern matching.

Java

public class TestJava21 {

    static String findData(Object obj) {

        return switch (obj) {

            case Integer a -> "Integer: " + a;

            case String msg -> "String: " + msg;

            case null -> "Null value";

            default -> "Unknown";

        };

    }


    public static void main(String[] args) {

        System.out.println(findData("Java"));

        System.out.println(findData(42));

        System.out.println(findData(null));

    }

}

Key Benefits:

  • Cleaner and more expressive code
  • Built-in null handling in switch
  • Avoids explicit casting

This is one of the most practical Java 21 features for writing clean, type-safe code.


2. Record Patterns (JEP 440)

Next on the list of Java 21 features is Record Patterns, which allows the deconstruction of record objects into their components within instanceof and switch statements.

Java

record Student(String name, int age) {}


public class TestJava21Features {

    public static void main(String[] args) {

        Object ob1 = new Student("Ajay", 30);

        Object ob2 = "Not a Student";


        greet(obj1);

        greet(obj2);

    }


    static void greet(Object obj) {

        if (obj instanceof Student(String name, int age)) {

            System.out.println("Hi, " + name + ". What is your " + age + "?");

        } else {

            System.out.println("Not known object.");

        }

    }

}

This Java 21 features that improve object destructuring in a way Java never could before.


3. Virtual Threads (JEP 444)

One of the game-changing Java 21 features is Virtual Threads, a part of Project Loom. This feature revolutionizes Java’s concurrency model.

What Are Virtual Threads?The overhead of concurrent programming is significantly reduced by these lightweight threads. You can spawn thousands or millions of virtual threads without exhausting system resources.

Java

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;


public class TestJava21Features {

    public static void main(String[] args) {

        // Creating an executor that launches a new virtual thread per task

        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {

            executor.submit(() -> {

                System.out.println("Running in: " + Thread.currentThread());

            });

        } // Executor closes automatically here

    }

}

Advantages:

  • Massive scalability
  • Simplifies asynchronous programming
  • Ideal for high-throughput web servers and microservices

If you're building concurrent systems, this is one of the most important Java 21 features to explore.


4. Unnamed Classes and Instance Main Methods (JEP 445 – Preview)

One of the more beginner-friendly Java 21 features is the support for Unnamed Classes and Instance Main Methods. This is a huge win for newcomers and scripting.

Unnamed Classes and Instance Main Methods in Java 21 are perfect for teaching beginners—but Eclipse doesn’t yet support this feature out-of-the-box, since it requires preview features, and unnamed classes can't be created as regular .java files.

However, I can still explain and demo it properly with a few alternatives.

Create a file named Hello.java in notepade with this content:

Java

void main() {

    System.out.println("Hello, Java 21 Features!");

}

Now run the above file in command prompt.

Plaintext

C:\Users\Admin\Desktop>java --enable-preview --source 21 Hello.java

Hello, Java 21 Features!

Use Cases:

  • Teaching Java without boilerplate code
  • Running simple Java scripts
  • Improving quick prototyping and learning

This feature makes Java more accessible, especially in educational environments.


5. String Templates (JEP 430 – Preview)

Another exciting entry in the list of Java 21 features is String Templates, a preview feature that introduces string interpolation in Java.

Why It’s Needed:Traditionally, Java has relied on + for string concatenation or String.format(), which can be error-prone and hard to read.

Java

public class TestJava21Features {

    public static void main(String[] args) {

        String name = "Ajay";

        String greeting = STR."Hi, \{name}!";

        System.out.println(greeting); // Output: Hi, Ajay!

    }

}

We can run the above program using the command line.

Plaintext

C:\Users\Admin\Desktop>javac --enable-preview --release 21 TestJava21Features.java

Note: It is using preview features .

C:\Users\Admin\Desktop>java --enable-preview TestJava21Features

Hello, Ajay!

Benefits:

  • Cleaner syntax for dynamic strings
  • Prevents formatting errors
  • Improves code readability

These are the following Java 21 features that directly enhance developer productivity and clarity.


Summary of Java 21 Features

String Templates: Easy string formatting

Record Patterns:  Simplifies pattern matching

Pattern Matching for switch: Safer and cleaner switch code

Virtual Threads: Scalable concurrency

Sequenced Collections: Maintains order in collections

Scoped Values: Safe value sharing in threads

Foreign Function & Memory API: Better native code support

Unnamed Classes: Simpler for beginners

Finalization Deprecation: Better memory handling


6. Scoped Values (JEP 446 – Preview)

If you’ve worked with ThreadLocal, you’ll love this addition to Java 21 features. Scoped Values offer a safer, immutable alternative.

Java

public class TestJava21Features {

    static final ScopedValue<String> PERSON = ScopedValue.newInstance();


    public static void main(String[] args) {

        ScopedValue.where(PERSON, "admin").run(() -> {

            System.out.println("Inside scoped block: " + PERSON.get()); // Output: admin

        });


        // Uncommenting below will throw IllegalStateException since we're outside the scope

        // System.out.println("Outside scoped block: " + USER.get());

    }

}

Plaintext

C:\Users\Admin\Desktop>javac --enable-preview --release 21 TestJava21Features.java

C:\Users\Admin\Desktop>java --enable-preview TestJava21Features

Inside scoped block: admin


7. Structured Concurrency (JEP 453 – Preview)

This Java 21 feature helps group related tasks, manage them as a unit, and ensure proper cleanup.

Why It’s Important:Traditional concurrent programming can easily lead to dangling threads and poor error handling. Structured concurrency brings a new structure to async programming, improving reliability.


8. Foreign Function & Memory API (JEP 442 – Preview)

For developers working close to native code, this is a standout among Java 21 features. It allows calling C libraries and working with native memory safely and efficiently.

Key Use Cases:

  • High-performance computing
  • Low-level system programming
  • Avoiding unsafe and complex JNI (Java Native Interface)

So, finally, these are some Java 21 features that make this LTS release a major upgrade. Whether you care about performance, code clarity, scalability, or developer experience, Java 21 has something for you.

With its blend of finalized features and cutting-edge previews, Java 21 empowers developers to write modern, readable, and highly concurrent code. From pattern matching to virtual threads, the platform is evolving rapidly while staying true to its core strengths of reliability and cross-platform support.

This is the ideal moment to try Java 21 if you haven't already. With long-term support and a host of new tools, Java 21 features are here to make your next project smarter, faster, and more enjoyable to build.

9. Sequenced Collections (JEP 431) 

Java 21 introduces Sequenced Collections, which provide a consistent way to work with collections that maintain order. A new interface added: SequencedCollection, SequencedSet, and SequencedMap. These collections maintain a consistent sequence of elements, improving reliability. You can easily get the first and last elements.


SequencedSet<String> names = new LinkedHashSet<>();

names.add("A");

names.add("B");

System.out.println(names.getFirst()); // A

System.out.println(names.getLast());  // B


Benefits:

  • Better support for ordered collections
  • SevenMentor
  • Easier access to first and last elements
  • SevenMentor
  • Cleaner collection APIs
  • SevenMentor
  • More consistent developer experience
  • SevenMentor


10. Deprecation of Finalization & Performance Improvement 

Java 21 officially deprecated finalization (using the finalize() method). Finalization has long been known for being unreliable and slow, which is why it's being phased out. Developers should use try-with-resources or the Cleaner API instead. Along with new features, Java 21 also brings better Garbage Collection (GC) performance (including Generational ZGC), faster startup time, improved security features, and smaller memory usage with virtual threads.

Real-World Use Cases & Migration Guidance

  • Backend & Payments: In a payment system, if there are different payment types such as card, UPI, or net banking, pattern matching allows the code to handle them more clearly inside a switch statement. Similarly, record patterns are helpful in DTOs and API response objects, while structured concurrency is especially useful in modern backend systems where multiple service calls happen in parallel.
  • SevenMentor+ 1
  • Upgrading from Older Versions: If you're using an older version like Java 8 or 11, Java 21 is a major upgrade. Being an LTS version, it's stable and future-proof. Companies and developers are encouraged to migrate because of long-term support, better performance, modern syntax, and easier concurrent programming.

Do visit our channel to explore more:  SevenMentor

Author:- Kiran Tiwari

Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.

All articles by Kiran Tiwari

#Technology#Education#Career Guidance