NashTech Blog

Table of Contents

Java, one of the most widely used programming languages, continues to evolve with each new release. Java 21 brings several exciting features and enhancements, further solidifying its position as a versatile and powerful language for building a wide range of applications. In this blog post, we’ll explore some of the key features introduced in Java 21.

Java, a cornerstone of modern software development, has seen a remarkable evolution over the years. With each new release, Java has introduced groundbreaking features and enhancements, making it one of the most versatile and widely used programming languages in the world. Before we dive into the exciting features of Java 21, let’s take a brief look at some of the key advancements in previous JDK versions beyond JDK17.

Java Releases done till java 21, and upcoming releases in future.

JDK18 overview

Embracing UTF 8 (Character encoding mechanism):

Before jdk18 encoding was defined in Host OS and Locale like UTF-8, but now its by default UTF-8, data transfer will be encoded by default with UTF 8.

Code Snippets in API documentation:

 @snippet tag introduced, developer may define the purpose of specific code.

public class StringUtils {
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
/**
* This snippet demonstrates how to use the StringUtils.reverse method to reverse a string.
*
* {@code
* String original = "Hello, World!";
* String reversed = StringUtils.reverse(original);
* System.out.println("Reversed string: " + reversed);
* }
*/
}

Vector API:

used for complex computations, scientific calculator, machine learning algo.

Foreign Function and Memory API:

low level language can be used by this in high level language(outside java runtime)(like from C to Java.

Simple Web Server:

Provide a CLI tool to start a minimum web server thatserve static files. It’s useful for testing, prototype, education purposes. You canuse – SimpleFileServer,HttpHandler, and Request.

Use command jwebserver to start server, -p to specific port.

Pattern matching Improvements:

Second preview of pattern matching for switch expressions.It allow us to express complex data-oriented queries in concise and safe way when using in switch statements.

Deprecated Finalization for Removal:

Finalization was introduced in Java 1.0 to avoid resource leak. It was deprecated in Java9 now removed.Reason there was performance issue.

Internet Address Resolution:

This defines a Service provider interface for host name and address resolution. Normally JDK uses OS’s native resolver, but now user is ableto implement an alternative resolver.

JDK 19: Valuable addition

DateTimeFormatter enchrichments:

ofLocalizedPattern() method added in Java 19. The DateTimeFormatter class in Java is crucial for parsing and formatting date-time objects. Adding the ofLocalizedPattern() method could be valuable for developers because it enhances the flexibility and localization capabilities of date-time formatting.

 


public class Example {
public static void main (String [] args) {
// Create a formatter for a custom pattern
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
// Create a formatter for a localized pattern
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedPattern(FormatStyle.SHORT);
// Format a date using the localized pattern
String localizedFormattedDate = localizedFormatter.format(LocalDate.now());
System.out.println("Localized formatted date: " + localizedFormattedDate);
}
}

Pre-allocated HashMap & HashSet:

Java 19 addresses a common misunderstanding about HashMap initialization parameters. It introduces factory methods that allow developers to specify the exact number of mappings they need, rather than relying on a capacity argument. This change simplifies HashMap creation and ensures accurate memory management and performance optimization. For example, instead of manually calculating capacity based on load factor, developers can now use HashMap.newHashMap(60) to create a HashMap with 60 mappings.

JDK 20 features

Lossy conversions​:

Warnings added in java 20.
Lossy conversions, also known as narrowing conversions, occur when you convert data from a type with a wider range of values to a type with a narrower range. For example, converting a double to an int or a float to a short can result in loss of precision or information because the destination type cannot represent all the possible values of the source type.

Deprecation: java.net.URL public Constructors​:

Deprecating the public constructors of java.net.URL in favor of using java.nio.file.Path and java.net.URI for creating URLs is a significant change in Java. This shift reflects a modern approach to handling file paths and URLs in Java, leveraging the improved file system operations introduced in the java.nio.file package.

URI uri = Paths.get( “/Users/your_user_name/example.txt” ).toUri();

Overview of Java 21 new features:

1. Pattern Matching for Switch Statements

Pattern matching for switch statements is a significant enhancement introduced in Java 21. This feature allows developers to use pattern matching with the switch statement, enabling concise and readable code for conditional logic. With pattern matching, developers can easily extract values from objects and perform actions based on their properties.

Traditional switch statements have been limited to simple equality checks.Pattern matching introduces a more expressive and concise syntax to switch statements.​​

  • Enhanced Expressiveness: Pattern matching enables switch statements to match complex patterns rather than just equality.
  • Concise Syntax: The new syntax reduces verbosity and makes code more readable.
  • Improved Readability: By allowing more expressive matching conditions, code becomes easier to understand.
  • Reduced Boilerplate: Pattern matching eliminates the need for repetitive type casting and instanceof checks.

2. Sequenced Collections

Java 21 introduces new features enhancing sequenced collections, offering improved performance and flexibility. 3 new interfaces are added in collection framework.

SequencedCollection, SequencedSet,SequencedMap:​

  • ArrayList Enhancements:Optimized resizing algorithm for improved performance.Reduced memory overhead with more efficient storage.
  • LinkedList Improvements:Enhanced node management for better performance.Streamlined operations for insertion and deletion.
  • Deque Interface Enhancements:Additional methods for bulk operations and iteration.Improved compatibility with existing collections framework.

Benefits:

  • Increased Performance: Optimizations lead to faster operations on sequenced collections.
  • Reduced Memory Usage: Efficiency improvements result in lower memory overhead.
  • Enhanced Functionality: Additional methods provide more flexibility and convenience.

3. Records Enhancements

Records, introduced in Java 14, are classes that act as transparent carriers for immutable data. In Java 21, records have been enhanced to support pattern matching and sealed types, making them even more powerful and flexible for modelling data in applications.

  • Introduction to records as a new type of declaration. Records are a new type of declaration introduced in Java.
  • Records provide a compact syntax for declaring data-holding classes.
  • Automatically generate accessor methods, equals()hashCode(), and toString() methods.
  • Advantages of using records for immutable data.
  • Concise declaration and initialization of immutable objects.
  • Enhanced readability and maintainability of code.
  • Code snippet illustrating the syntax of records.
  • Example of declaring a record class with fields.
record Point(int x, int y) {}
Point p = new Point(10, 20);
if (p instanceof Point point) {
System.out.println("Point coordinates: " + point.x() + ", " + point.y());
}

4. Sealed Types

Sealed types provide a mechanism for restricting the subclasses of a class or interface. In Java 21, sealed types have been enhanced to support pattern matching, allowing developers to write more expressive and concise code when working with sealed types and their subclasses.

sealed interface Shape permits Circle, Rectangle {
// methods...
}
class Circle implements Shape {
// Circle implementation...
}
class Rectangle implements Shape {
// Rectangle implementation...
}
// Pattern matching with sealed types
public static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
};
} 

5. Enhanced Foreign Function Interface (FFI)

Java 21 introduces enhancements to the Foreign Function Interface (FFI), enabling better integration with native code libraries and improved performance for interop scenarios. These enhancements make it easier for developers to call native code from Java and vice versa, opening up new possibilities for building high-performance applications.

// Example of calling a native function from Java using FFI
public native void nativeFunction();

6. Enhanced Pattern Matching for instanceof

Pattern matching for instanceof is another feature introduced in Java 21. This feature allows developers to use pattern matching with the instanceof operator, making it easier to perform type checks and type casts in a more concise and readable manner.

// Example of pattern matching with instanceof
if (obj instanceof String str && str.length() > 5) {
System.out.println("String is longer than 5 characters: " + str);
}

7. Improved Packaging Tool

Java 21 includes improvements to the packaging tool (jpackage), which allows developers to package Java applications as native executables for distribution on various platforms. The enhanced packaging tool offers better support for custom runtime images and improved performance when creating native installers.

8. Deprecation of Nashorn JavaScript Engine

In Java 21, the Nashorn JavaScript engine has been deprecated and is no longer included in the JDK. Developers are encouraged to migrate to alternative JavaScript engines such as GraalVM for running JavaScript code in Java applications.

9. Performance Improvements

As with every new release, Java 21 includes various performance improvements and optimizations to make Java applications faster and more efficient. These optimizations include enhancements to the JVM compiler, garbage collector, and runtime libraries, resulting in better overall performance for Java applications.

Conclusion

Java 21 brings several exciting features and enhancements that further improve the language’s usability, expressiveness, and performance. From pattern matching to sealed types and enhanced FFI, Java 21 empowers developers to write cleaner, more concise code and build high-performance applications with ease. As always, it’s recommended to stay updated with the latest Java releases to take advantage of the newest features and improvements.


This blog provides an overview of some of the key features introduced in Java 21 and their potential impact on Java development.

For more: look into below.

https://openjdk.org/projects/jdk/21/

For further insights, please visit this blog.

Picture of Chitra Singh

Chitra Singh

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top