Java 17 Features
- Anand Nerurkar
- Oct 4, 2023
- 4 min read
Updated: May 27, 2024
Java 17 language API Enhancement
1. Record Keyword
Java 17 also introduces a new Records feature, which allows you to create simple data classes in a more concise and readable way.
A record is a class that represents a logical tuple of values, and it provides a number of helpful features such as automatic constructors and accessor methods.
When we need to create immutable object, then we can use record.
Record is final , can not extend class but can implement interface
by default all fields in record are final, can not define instance variable, but static variable is allowed
For example:
record Person(String firstName, String lastName, int age) {
// The record class automatically defines accessor methods for its fields,
// as well as a constructor and toString() method.
// You can also define additional methods and fields within the record class,
// if necessary.
}
This code defines a Person record that has three fields: firstName, lastName, and age. You can then create instances of this record and access its fields like this:
Person person = new Person("John", "Doe", 35);
String firstName = person.firstName();
String lastName = person.lastName();
int age = person. Age();
As you can see, the Records feature provides a simple and intuitive way to define and use data classes in your Java code.
2.Sealed Classes & Interfaces
When we define classes or interface, anyone can implement that interface ot extend that class.There is no provision for the restriction as a part of security.
With introduction of Sealed classes,give us the privilege of controlling which classes or models can implement or extend that interface or class respectively. It represents restricted class hierarchies that provide control over an inheritance.
For a sealed class, all direct subclasses need to be known at compile-time and third-party clients can’t extend a sealed class in their code. To make a Java class, a sealed Java class, add the sealed modifier to its declaration, and keyword permits are placed to indicate the classes which are permitted for the given sealed class.
public sealed class Shape permits, Square, Rectangle, Circle { }
OR
public sealed interface Shape permits, Square, Rectangle, Circle { }
With above declaration, it make sure that only Square,Rectangle,Circle can implement/extend sealed class or interface.
3.Pattern Matching for the instanceOf operator
Pattern matching allows you to use the instanceof operator in a more concise and expressive way.
For example, you can use it to check if a value is an instance of a particular type and then extract that value in a single step. Here’s an example:
if (obj instanceof String s && s.length() > 10) {
System.out.println(s.substring(0, 10) + "...");
}
4.Foreign Function and Memory API
This API enables Java developers to access and call native functions and libraries written in other programming languages like C and C++.
Additionally, it allows Java applications to allocate and manage native memory outside of the Java heap, which can be beneficial for performance-intensive tasks.
The Foreign Function and Memory API provides a simple and consistent way to interact with non-Java code and resources while maintaining the safety and security of the Java environment.
How Foreign Function and Memory API can be used
1.Calling a C function from Java:
Suppose you have a C function that you want to call from Java. With the Foreign Function and Memory API, you can define a Java interface that corresponds to the C function’s signature and call the function as if it were a Java method.
2.Using a C library from Java:
Many popular libraries, such as OpenSSL and FFmpeg, are written in C or C++. With the Foreign Function and Memory API, you can load these libraries into your Java application and use their functions as if they were Java methods.
3.Allocating native memory:
In some cases, you may need to allocate memory outside of the Java heap to improve performance. With the Foreign Function and Memory API, you can allocate and manage native memory directly from your Java code, using familiar Java syntax and semantics.
5. Text Blocks
This allows you to create multi-line strings in a more convenient and readable way.
For example:
String html = """
<html>
<body>
<p>Hello, world!</p>
</body>
</html>
""";
As you can see, the Text Blocks feature allows you to create multi-line strings without having to use escape characters or concatenation. This makes it easier to create strings that contain multiple lines of text, such as HTML or JSON.
6. Redefining Switch Statement Expressions
The new switch expressions are less error-prone as it is cleaner and simpler now. The use of arrow symbols not only eliminates the fall-through functionality but also makes it more readable and easy to debug.
We can include more than one value in the same block by comma separating them. One of the important features is the introduction of the yield keyword. In the code snippet, on the execution of the default statement, System.out.println() will execute and the identifyTyres variable will end up to be “Unknown Vehicle” because this is what the default is meant to yield.
String identifyTyres = switch (vehicle) {
case Car -> “four”;
case Bike, Cycle -> “two”;
case Autorickshaw -> “three”;
default -> { System.out.println(“The vehicle could not be found.”);
yield “Unknown Vehicle”;
};
7. End of Guessing the Cause of Null Pointer Exception
NullPointerException guidance feature of Java 17 comes as a friend indeed as it provides the exact name of the variable that is null from the exception’s stack trace. Thus, this feature saves us from debugging hassle and ends up the guessing game of finding out the pointer which went null.
8. ZGC Garbage Collector
This collector is designed to improve the performance of Java applications by reducing the amount of time spent on garbage collection. With the ZGC garbage collector, applications can achieve pause times of less than 10 milliseconds, even when working with large heaps. Here’s an example of how to enable the ZGC garbage collector in your code:
// Enable the ZGC garbage collector
-XX:+UseZGC
9. Null in Switch-Case expression
With this feature, we can put null as a selector expression in switch case expressions.
Consider the below example where we can pass null as a selector expression.
switch(selectCase) {
case 1,7 -> System.out.println(“odd number”) ;
case 2,8 -> System.out.println(“even number”) ;
case null -> System.out.println(“Not defined”) ;
default -> System.out.println(“not a number”) ;
}
Here, selectCase variable gets a number as an input. If null is passed as an input, “Not defined” is displayed as an output.
Comments