Java 21: New Features and Sample Code

Introduction: Java 21 is the latest release of the popular programming language, bringing a range of exciting features and improvements. In this article, we will explore some of the noteworthy additions in Java 21 and provide sample code to demonstrate their usage. Let’s dive in!

Pattern Matching for Switch:

One of the most anticipated features in Java 21 is the enhancement to switch statements with pattern matching. This simplifies the process of writing complex switch cases by allowing developers to extract variables and perform type checks directly within the switch block. Here’s an example:

public String processObject(Object obj) {
    return switch (obj) {
        case String s -> "Received a string: " + s;
        case Integer i && i > 0 -> "Received a positive integer: " + i;
        case Integer i -> "Received an integer: " + i;
        default -> "Received an unknown object";
    };
}

Records:

Java 14 introduced the concept of records as a concise way to declare classes that are primarily used for holding data. In Java 21, records receive additional enhancements, such as the ability to declare records locally within a block scope. Here’s an example:

public void processRecords() {
    record Person(String name, int age) { }

    Person person = new Person("John", 25);
    System.out.println(person.name()); // Output: John
    System.out.println(person.age());  // Output: 25
}

Sealed Classes:

Sealed classes provide control over class inheritance by restricting which classes can be subclasses. This feature enhances encapsulation and allows for more robust code. In Java 21, sealed classes receive further improvements, including the ability to declare them within a single file. Here’s an example:

sealed interface Animal permits Dog, Cat, Bird { }

final class Dog implements Animal { }

final class Cat implements Animal { }

final class Bird implements Animal { }

Foreign Function & Memory API:

Java 21 introduces the Foreign Function & Memory API, which allows Java programs to interact with native code more seamlessly. This feature provides the ability to call functions in shared libraries and work with native memory directly. Here’s an example:

import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemorySegment;
import static jdk.incubator.foreign.CLinker.*;

public void callNativeFunction() {
    try (var scope = MemoryScope.stackScope()) {
        var segment = C_POINTER.create(segmentSize()).copyFrom(new byte[segmentSize()]);
        MemoryAddress address = segment.baseAddress();
        C_POINTER.get().addressOf(C_POINTER.get().symbolLookup().lookup("myFunction")).invokeExact(address);
    }
}

Conclusion:

Java 21 brings exciting enhancements to the language, including pattern matching for switch, records, sealed classes, and the Foreign Function & Memory API. These features aim to improve developer productivity, code readability, and interoperability. As you explore Java 21, make sure to leverage these features to write cleaner and more expressive code.

Note: Java 21 is a fictional version, and the provided sample code may not reflect the actual syntax or behavior of future Java releases.

Next Steps :

Learn Spring Boot

Angular Template

Leave a Reply

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping