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);
}
}
}
๐ฏ 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";
};
}
๐ฆ 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.");
}
}
๐ฌ 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);
--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]
๐ 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);
}
๐น 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.