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.
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.
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.
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:
void main() {
System.out.println("Hello, Java 21 Features!");
}
Now run the above file in command prompt.
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.
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.
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.
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.
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());
}
}
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.
Do visit our channel to explore more: SevenMentor
Author:- Kiran Tiwari
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.