Introduction
Java 21 introduces a range of exciting new features and enhancements that improve the language’s expressiveness, performance, and developer productivity. This article explores some of the most significant updates in Java 21, complete with practical examples to illustrate their usage.
1. Pattern Matching for switch (Third Preview)
Pattern matching for switch
enhances the switch
statement and expression by allowing patterns to appear in case labels. This feature simplifies code that conditionally extracts components from objects.
Example:
public class PatternMatchingSwitch {
public static void main(String[] args) {
Object obj = "Hello, Java 21";
String result = switch (obj) {
case String s -> "String: " + s;
case Integer i -> "Integer: " + i;
case null -> "null value";
default -> "Unknown type";
};
System.out.println(result); // Output: String: Hello, Java 21
}
}
In this example, the switch
statement uses pattern matching to handle different types of objects.
2. Record Patterns (Second Preview)
Record patterns simplify the deconstruction of record values, making it easier to work with data in records.
Example:
public record Point(int x, int y) {}
public class RecordPatternExample {
public static void main(String[] args) {
Point point = new Point(3, 4);
String result = switch (point) {
case Point(int x, int y) -> "Point coordinates: " + x + ", " + y;
default -> "Unknown";
};
System.out.println(result); // Output: Point coordinates: 3, 4
}
}
Here, the switch
statement uses record patterns to deconstruct the Point
record and access its components directly.
3. String Templates (Preview)
String templates allow for more readable and maintainable string interpolation, similar to what is available in other programming languages.
Example:
public class StringTemplateExample {
public static void main(String[] args) {
String name = "Java";
int version = 21;
String message = STR."Hello, \{name} \{version}!";
System.out.println(message); // Output: Hello, Java 21!
}
}
In this example, the STR
syntax enables string interpolation, making it easier to construct strings with embedded expressions.
4. Sequenced Collections
Sequenced collections introduce a new interface that provides a unified way to work with collections that have a defined encounter order, like lists and deques.
Example:
import java.util.*;
public class SequencedCollectionsExample {
public static void main(String[] args) {
SequencedCollection<String> sequencedList = new LinkedList<>(List.of("one", "two", "three"));
sequencedList.addFirst("zero");
sequencedList.addLast("four");
System.out.println(sequencedList); // Output: [zero, one, two, three, four]
}
}
In this example, a LinkedList
implements the SequencedCollection
interface, providing methods to manipulate elements based on their encounter order.
5. Virtual Threads (Preview)
Virtual threads simplify writing and maintaining high-throughput concurrent applications by making threads lightweight and more scalable.
Example:
public class VirtualThreadsExample {
public static void main(String[] args) throws InterruptedException {
Thread.startVirtualThread(() -> {
System.out.println("Hello from virtual thread");
}).join();
}
}
In this example, a virtual thread is created and started using Thread.startVirtualThread
, providing a lightweight alternative to traditional threads.
6. Enhanced Networking and Security
Java 21 includes various enhancements in networking and security, such as improved TLS support and more robust HTTP/2 handling.
Example: Using HTTP/2 Client
import java.net.http.*;
public class Http2ClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://http2.example.com"))
.version(HttpClient.Version.HTTP_2)
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
In this example, the HttpClient
is configured to use HTTP/2, demonstrating improved support for modern web standards.
Conclusion
Java 21 introduces a host of new features that enhance the language’s capabilities and improve developer productivity. From pattern matching for switch
and record patterns to string templates and virtual threads, these updates offer more expressive and efficient ways to write Java code. As you explore these new features, consider how they can simplify and improve your projects. Java continues to evolve, providing powerful tools for modern software development.
“Really informative post. Learned a lot!”