Java 21 has introduced new features, that helps to enhance productivity, performance and easy of coding. Lets see below the latest enhancements which are introduced in Java 21.
String template which allow us to create more readable and maintainable string concatenations. It eliminates the need for the cumbersome + operator or String.format().
Before JDK21:
String name = "Sadakhat";
int age = 35;
String message = "My name is " + name + " and I am " + age + " years old.";
With String templates:
String name = "Sadakhat";
int age = 35;
String message = STR."My name is \{name} and I am \{age} years old.";
This feature makes the code cleaner and more expressive. Additionally, it supports nesting and multiline strings.
Java21 has introduced Record Pattern which more aligned with functional programming. Record Patterns allow you to deconstruct objects concisely.
Before JDK21:
record Person(String name, int age) {}
void printPerson(Object obj) {
if (obj instanceof Person) {
Person p = (Person) obj;
System.out.println("Name: " + p.name() + ", Age: " + p.age());
}
}
With Record Pattern:
void printPerson(Object obj) {
if (obj instanceof Person(String name, int age)) {
System.out.println("Name: " + name + ", Age: " + age);
}
}
The new syntax reduced boilerplate and make the code more readable.