Skip to Content
Technical Articles
Author's profile photo Dhiraj Jaiswal

Java 17 – Best Practices and features

Introduction: The goal of OpenJdk organisation is to develop updates for the Java Development Kit (JDK) Project. This blog compiles all the major feature changes that were introduced between Java 11 to Java 17. As Java 17 will have LTS support, migrating existing application to java 17 make application secure and reduces vulnerability. Therefore it is important and beneficial for developer to use latest features of java 17 while coding as part of best practices and it also improves developer experience. Top features are discussed below:

  • [Text Blocks](#text-blocks)
  • [Switch Expressions](#switch-expressions)
  • [Stream.toList()](#streamtolist)
  • [Records](#records)
  • [Sealed Classes](#sealed-classes)
  • [Pattern matching for instanceof](#pattern-matching-for-instanceof)
  • [Other remarkable features:](#other-remarkable-features)
  • [Reference](#reference)

Text Blocks

In java 17, we can add multi line string in Java now using `”””` triple quotes.It facilitates the preservation of indents and multiple lines without adding white spaces in quotes
Example
private static void jsonBlock() {
String text = """
{
"name": "Dhiraj Jaiswal",
"job": "Software developer"
}
""";
System.out.println(text);
}
No need for escaping the double quotes and it looks just like it will be printed.

Switch Expressions

Switch Expressions will allow you to return values from the switch and use these return values in assignments, etc. a new switch…case statement has been introduced in a less verbose form.
Example
private static void withYield(Fruit fruit) {
String text = switch (fruit) {
case MANGO, BANANA -> {
System.out.println("the given fruit was: " + fruit);
yield "Common fruit";
}
case ORANGE, APPLE -> "Exotic fruit";
default -> "Undefined fruit";
};
System.out.println(text);
}

New Stream.toList() method

Previously in order to convert a Stream to a List, you need to call the collect method with Collectors.toList(). Now we have stream.toList() method.
Stream<String> stringStream = Stream.of("a", "b", "c");
List<String> stringList = stringStream.toList();

Records

Records will allow you to create immutable data classes. No need to use lombok libraries for constructor, getters, hashCode, equals and toString etc. The resulted classes are immutable data-only classes, so there are no setters. It is possible to add a static method to record, and constructors. Record cannot extend
another class because it already extends java.lang.Record, but it can implement another interface.
public record Human(String name, float height, Gender gender) {

}

public class RecordDemo {
public static void main(String... args) {
Human dhiraj = new Human("Dhiraj Jaiswal", 1.9f, Gender.MALE);
System.out.println("Dhiraj as string: " + dhiraj);
System.out.println("Dhiraj's hashCode: " + dhiraj.hashCode());
System.out.println("Dhiraj's name: " + dhiraj.name());
}
}​

Sealed Classes

Provide access the super class only to specific packages.
Example: The only thing to do is to add the sealed keyword to the Fruit class and indicate with the permits keyword which classes may extend this Sealed Class. The subclasses need to indicate whether they are final, sealed or non-sealed. The super class cannot control whether a subclass may be extended and how it may be extended. In support sealed classes, the Java Reflections API in Java 17 has two new methods,
isSealed() and getPermittedSubclasses().
public abstract sealed class FruitSealed permits AppleSealed, PearSealed {
}
public non-sealed class AppleSealed extends FruitSealed {
}
public final class PearSealed extends FruitSealed {
}
The sealed interface integrates well with record because record is final and can be
listed as a permittable implementation.

Pattern matching for instanceof

It is possible to create the variable in the instanceof check and the extra line for creating a new variable and casting the object, is not necessary anymore.
private static void patternMatching() {
     Object o = new GrapeClass(Color.BLUE, 2);
     if (o instanceof GrapeClass grape) {
         System.out.println("This grape has " + grape.getNbrOfPits() + " pits.");
     }
}

Other remarkable features:

  • Helpful NullPointerExceptions. It shows exactly where the NullPointerException occured.
  • Compact number formattiing support. (1k,1M etc)
  • Day Period Support Added. (Ex: in the morning etc)
  • Context-Specific Deserialization Filters.
  • Enhanced Pseudo-Random Number Generators.
  • Vector API and Foreign function.
  • The Z Garbage Collector (ZGC) is no longer an experimental feature. Enable ZGC by using the command-line option XX:+UseZGC.
  • JavaDoc can now generate a page summarizing the recent changes in an API.

Reference

  1. Java_17_for_Absolute_Beginners, more java 17 : an in-depth exploration of the java language and its features
  2. Learn Java 17 Programming Second Edition
  3. https://www.baeldung.com/java-17-new-features
  4. https://wiki.openjdk.org/display/JDKUpdates/JDK+17u

Please share your thoughts about this blog in the comment section.

Please follow my Dhiraj Jaiswal for future posts.

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.