What's New in Java 21: Key Features and Examples

 

What's New in Java 21: Key Features and Examples

Java 21, released in September 2024, brings several significant enhancements to the language, building on its strong foundation while introducing features aimed at improving developer productivity and application performance. Here’s a rundown of the key features in Java 21, along with examples to illustrate their use.

1. Pattern Matching for Switch Expressions

Java 21 extends pattern matching to switch expressions, allowing for more concise and readable code. This feature simplifies the process of branching based on the type or value of an object.

Example:

java
public class PatternMatchingDemo { public static String getDayType(String day) { return switch (day) { case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday"; case "Saturday", "Sunday" -> "Weekend"; default -> throw new IllegalArgumentException("Invalid day: " + day); }; } public static void main(String[] args) { System.out.println(getDayType("Monday")); // Output: Weekday System.out.println(getDayType("Sunday")); // Output: Weekend } }

2. Record Patterns

Record patterns allow deconstructing record objects in a more readable and expressive way, enhancing the ease of working with data models.

Example:

java
public record Person(String name, int age) {} public class RecordPatternDemo { public static String describePerson(Object obj) { return switch (obj) { case Person(String name, int age) when age >= 18 -> name + " is an adult."; case Person(String name, int age) -> name + " is a minor."; default -> "Unknown person"; }; } public static void main(String[] args) { Person john = new Person("John", 30); Person alice = new Person("Alice", 15); System.out.println(describePerson(john)); // Output: John is an adult. System.out.println(describePerson(alice)); // Output: Alice is a minor. } }

3. Virtual Threads

Virtual threads provide a new way to handle concurrency, making it easier to write scalable and efficient applications. They offer a lightweight alternative to platform threads.

Example:

java
import java.util.concurrent.Executors; public class VirtualThreadsDemo { public static void main(String[] args) { var executor = Executors.newVirtualThreadExecutor(); for (int i = 0; i < 5; i++) { executor.submit(() -> { System.out.println("Running in virtual thread: " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } executor.shutdown(); } }

4. Enhanced switch Statements

Java 21 enhances the switch statement with the ability to use expressions directly, making code more compact and expressive.

Example:

java
public class EnhancedSwitchDemo { public static void main(String[] args) { int dayOfWeek = 3; // Wednesday String dayName = switch (dayOfWeek) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; case 4 -> "Thursday"; case 5 -> "Friday"; case 6 -> "Saturday"; case 7 -> "Sunday"; default -> throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeek); }; System.out.println(dayName); // Output: Wednesday } }

5. Sealed Interfaces and Classes

Sealed classes and interfaces restrict which other classes or interfaces can extend or implement them. This feature is useful for maintaining a controlled class hierarchy.

Example:

java
public sealed interface Shape permits Circle, Rectangle {} public final class Circle implements Shape { private final double radius; public Circle(double radius) { this.radius = radius; } // Getter, toString(), etc. } public final class Rectangle implements Shape { private final double width; private final double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } // Getter, toString(), etc. }

Conclusion

Java 21 introduces several powerful features that enhance the language’s expressiveness, improve code readability, and streamline concurrency management. By adopting these new features, developers can write more efficient and maintainable code, keeping Java at the forefront of modern programming languages.

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation