Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

1. Overview

In this article, we’ll discuss the new features and enhancements that have been added to Java 21.

Java 21, released on September 19, 2023, is the latest LTS version after the previous Java 17.

2. List of JEPs

Next, we’ll talk about the most notable enhancements, also called Java Enhancement Proposals (JEP), the new version of the language introduced.

2.1. Record Patterns (JEP 440)

Record patterns were included in Java 19 and Java 20 as preview features. Now, with Java 21, they are out of the preview and include some refinements.

This JEP extends the existing pattern-matching feature to destructure the record class instances, which enables writing sophisticated data queries. Moreover, this JEP adds support for nested patterns for more composable data queries.

For example, we can write code more concisely:

record Point(int x, int y) {}
    
public static int beforeRecordPattern(Object obj) {
    int sum = 0;
    if(obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        sum = x+y;
    }
    return sum;
}
    
public static int afterRecordPattern(Object obj) {
    if(obj instanceof Point(int x, int y)) {
        return x+y;
    }
    return 0;
}

As a consequence, we can also nest records within records and deconstruct them:

enum Color {RED, GREEN, BLUE}
record ColoredPoint(Point point, Color color) {}
record RandomPoint(ColoredPoint cp) {}
public static Color getRamdomPointColor(RandomPoint r) {
    if(r instanceof RandomPoint(ColoredPoint cp)) {
        return cp.color();
    }
    return null;
}

Above, we access the .color() method directly from ColoredPoint.

2.2. Pattern Matching for switch (JEP 441)

Initially introduced in JDK 17, Pattern matching for the switch was refined in JDK 18, 19, and 20 and improved further in JDK 21.

The main goal of this feature is to allow patterns in switch case labels and improve the expressiveness of switch statements and expressions. Besides, there is also an enhancement to handle NullPointerException by allowing a null case label.

Let’s explore this with an example. Suppose we have an Account class:

static class Account{
    double getBalance(){
       return 0;
    }
}

We extend this into various types of accounts, each having its method for calculating the balance:

static class SavingsAccount extends Account {
    double getSavings() {
        return 100;
    }
}
static class TermAccount extends Account {
    double getTermAccount() {
        return 1000;
    } 
}
static class CurrentAccount extends Account {
    double getCurrentAccount() {
        return 10000;
    } 
}

Before Java 21, we can use the below code to get the balance:

static double getBalanceWithOutSwitchPattern(Account account) {
    double balance = 0;
    if(account instanceof SavingsAccount sa) {
        balance = sa.getSavings();
    }
    else if(account instanceof TermAccount ta) {
        balance = ta.getTermAccount();
    }
    else if(account instanceof CurrentAccount ca) {
        balance = ca.getCurrentAccount();
    }
    return balance;
}

The above code isn’t very expressive as we have a lot of noise with the ifelse cases. With Java 21, we can leverage patterns in case labels to write the same logic more concisely:

static double getBalanceWithSwitchPattern(Account account) {
    double result = 0;
    switch (account) {
        case null -> throw new RuntimeException("Oops, account is null");
        case SavingsAccount sa -> result = sa.getSavings();
        case TermAccount ta -> result = ta.getTermAccount();
        case CurrentAccount ca -> result = ca.getCurrentAccount();
        default -> result = account.getBalance();
    };
    return result;
}

To confirm what we wrote is correct, let’s prove this with a test:

SwitchPattern.SavingsAccount sa = new SwitchPattern.SavingsAccount();
SwitchPattern.TermAccount ta = new SwitchPattern.TermAccount();
SwitchPattern.CurrentAccount ca = new SwitchPattern.CurrentAccount();

assertEquals(SwitchPattern.getBalanceWithOutSwitchPattern(sa), SwitchPattern.getBalanceWithSwitchPattern(sa));
assertEquals(SwitchPattern.getBalanceWithOutSwitchPattern(ta), SwitchPattern.getBalanceWithSwitchPattern(ta));
assertEquals(SwitchPattern.getBalanceWithOutSwitchPattern(ca), SwitchPattern.getBalanceWithSwitchPattern(ca));

So, we just rewrote a switch more concisely.

A pattern case label also supports matching against expressions for the same label. For example, suppose we need to process an input string that contains a simple “Yes” or “No“:

static String processInputOld(String input) {
    String output = null;
    switch(input) {
        case null -> output = "Oops, null";
        case String s -> {
            if("Yes".equalsIgnoreCase(s)) {
                output = "It's Yes";
            }
            else if("No".equalsIgnoreCase(s)) {
                output = "It's No";
            }
            else {
                output = "Try Again";
            }
        }
    }
    return output;
}

Again, we can see that writing ifelse logic can get ugly. Instead, in Java 21, we can use when clauses along with case labels to match the label’s value against an expression:

static String processInputNew(String input) {
    String output = null;
    switch(input) {
        case null -> output = "Oops, null";
        case String s when "Yes".equalsIgnoreCase(s) -> output = "It's Yes";
        case String s when "No".equalsIgnoreCase(s) -> output = "It's No";
        case String s -> output = "Try Again";
    }
    return output;
}

2.3. String Literal (JEP 430)

Java offers several mechanisms for composing strings with string literals and expressions. Some of these are String concatenation, StringBuilder class, String class format() method, and the MessageFormat class.

Java 21 introduces string templates. These complement Java’s existing string literals and text blocks by coupling literal text with template expressions and template processors to produce the desired results.

Let’s see an example:

String name = "Baeldung";
String welcomeText = STR."Welcome to \{name}";
System.out.println(welcomeText);

The above code snippet prints the text “Welcome to Baeldung“.

String Templates

In the above text, we have a template processor (STR), a dot character, and a template that contains an embedded expression (\{name}). At runtime, when the template processor evaluates the template expression, it combines the literal text in the template with the values of the embedded expression to produce the result.

The STR is one of Java’s template processors, and it is automatically imported into all Java source files. Java also offers FMT and RAW template processors.

2.4. Virtual Threads (JEP 444)

Virtual threads were initially introduced to the Java language as a preview feature in Java 19 and further refined in Java 20. Java 21 introduced some new changes.

Virtual threads are lightweight threads with the purpose of reducing the effort of developing high-concurrent applications. Traditional threads, also called platform threads, are thin wrappers around OS threads. One of the major issues with platform threads is that they run the code on the OS thread and capture the OS thread throughout its lifetime. There is a limit to the number of OS threads, and this creates a scalability bottleneck.

Like platform threads, a virtual thread is also an instance of java.lang.Thread class, but it isn’t tied to a specific OS thread. It runs the code on a specific OS thread but does not capture the thread for an entire lifetime. Therefore, many virtual threads can share OS threads to run their code.

Let us see the use of the virtual thread with an example:

try(var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.rangeClosed(1, 10_000).forEach(i -> {
        executor.submit(() -> {
            System.out.println(i);
            try {
                Thread.sleep(Duration.ofSeconds(1));
            } 
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    });
}

In the above code snippet, we’re using the static newVirtualThreadPerTaskExecutor() method. This executor creates a new virtual thread for each task, so in the above example, we create 10,000 virtual threads.

Java 21 introduced two notable changes to the virtual threads:

  • Virtual threads now always support thread-local variables.
  • Virtual threads are created through the Thread.Builder APIs are also monitored through their lifetime and observable in the new thread dump

2.5. Sequenced Collections (JEP 431)

In the Java collection framework, no collection type represents a sequence of elements with a defined encountered order.  For instance, List and Deque interfaces define an encounter order, but their common super type Collection doesn’t. In the same way, Set doesn’t define an encounter order, but subtypes such as LinkedHashSet or SortedSet do.

Java 21 introduced three new interfaces to represent sequenced collections, sequenced sets, and sequenced maps.

A sequenced collection is a collection whose elements have a defined encounter order. It has first and last elements, and the elements between them have successors and predecessors.  A sequenced set is a set that is a sequenced collection with no duplicate elements. A sequenced map is a map whose entries have a defined encountered order.

The following diagram shows the retrofitting of the newly introduced interfaces in the collection framework hierarchy:

Sequenced Collections

2.6. Key Encapsulation Mechanism API (JEP 452)

Key encapsulation is a technique to secure symmetric keys using asymmetric keys or public key cryptography.

The traditional approach uses a public key to secure a randomly generated symmetric key. However, this approach requires padding, which is difficult to prove secure.

A key encapsulation mechanism (KEM) uses the public key to derive the symmetric key that doesn’t require any padding.

Java 21 has introduced a new KEM API to enable applications to use KEM algorithms.

3. Conclusion

In this article, we discussed a few notable changes delivered in Java 21.

We discussed record patterns, pattern matching for switches, string templates, sequenced collections, virtual threads, string templates, and the new KEM API.

Other enhancements and improvements are spread across JDK 21 packages and classes. However, this article should be a good starting point for exploring Java 21’s new features.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)