Talk about what's new with Java 9-17

The introduction of Lambda expressions and streams in Java 8 has brought a functional programming style. In the future, the pace of java version release will be accelerated, and a new version will be switched every six months. Many new features may not be clear to many people. Although most of today's scenarios are Java 8, it is also necessary for every java programmer to understand industry changes. This article mainly introduces some new language features of Java 9 to 17. Some changes in the underlying implementation will be listed briefly.










Java 9

Java 9 is a relatively large update after Java 8, which contains many new features


Module is a new Java code access permission level. Each module can contain multiple package s.
Via module info Java file to declare the folder and its subfolders as a module. The exports keyword can be used to control which packages in the module are exposed.

 module store.api{

After using module, even if the class in the package is public, if its package is not explicitly exported through exports, the external module is not callable.
If a module wants to use the classes in the package exported by another module, it can use the requires keyword in its module info Java file to import (read) the package package of the target module.

 module store.service {

Java9 module is very similar to Maven module, but its functions are completely different. The latter is built as a dependency to facilitate the management of application code, while the Java Module is based on security and access control. The specific packages that need to be exposed and relied on in the module are controlled through exports / requirements.

Interface supports defining private methods

interface DemoI {
	private void privateMethod() {

Improved try with resources syntax

try() of the try with resources syntax can contain variables separated by semicolons.
After improvement, the semantics will be clearer and the syntax of resource creation and resource recycling will be split.

public void testTryWithResources(String fileName) {
    FileOutputStream fos = new FileOutputStream(fileName);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    BufferedWriter bw = new BufferedWriter(osw);
    try (bw;osw;fos) {
	  Compare Java 7:
	  try(FileOutputStream fos = new FileOutputStream(fileName);
      	  OutputStreamWriter osw = new OutputStreamWriter(fos);
      	  BufferedWriter bw = new BufferedWriter(osw);){

Enhanced Stream API

1,Stream. Take while (predict): process the data in the stream until the condition predict returns false, and then terminate the execution.

public void test() {
	Stream.of(1, 2, 3, 4, 5)
		.takeWhile(i -> i != 3)
	  Output results:

2,Stream. Dropwhile (predict): in contrast to taskWhile, it does not start processing the data in the subsequent stream until the condition predict returns false.

public void test() {
	Stream.of(1, 2, 3, 4, 5)
		.dropWhile(i -> i != 3)
	  Output results:

3,Stream.iterate: iterates through the data in the stream until the condition returns false
The method is defined as follows:

  * @param seed Initialize loop variable
  * @param hasNext Cycle condition
  * @param next Next cycle value
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)


public void test() {
	IntStream.iterate(1, x -> x < 10, x -> x + 5).forEach(System.out::println);
	  Output results:

4,Stream.ofNullable: for stream When creating a stream, an empty stream is returned for an empty input parameter


REPL, fully known as Read Eval Print Loop, "interactive interpreter", a real-time compiler that supports what you see is what you get.
Some simple code logic can be executed directly through Jshell without compiling with palace javac.

Coexistence of multiple Jdk versions

The same jar package can contain multiple Java versions of class files. Jars corresponding to jdk versions can be used in different jdk environments.
(this is a very user-friendly function for users)

Java 10

Local type inference

The new keyword var enables Java to automatically infer data types like js. Limited to local variables, it is a syntax sugar. The underlying layer has not changed. The actual type of variables is inferred at compile time.

var str = "show the var";

Other optimizations on the bottom layer are not expanded, but listed directly

  • Parallel Full GC for G1
  • Class data sharing
  • Java based JIT compiler (experimental)
  • ...

Java 11

Another version of LTS (long-term support) after Java 8. Since Java 11, Oracle JDK will no longer provide free commercial use.

StringAPI enhancements

1,String.isBlank(): empty the string before and after white space characters
2. lines(): split the string by line to get a character stream
3. repeat(): copy string
4. strip(): remove front and back white space characters (different from trim(), only half width spaces can be removed)

Local type inference enhancement

var is allowed in lambda expressions
  .map((@NotNull var x) -> x.toUpperCase()));

HTTP client enhancements

In Java 11, the Http Client API is supported by standardization. It also supports HTTP/1.1, HTTP/2 and websockets.

HttpRequest request = HttpRequest.newBuilder()
HttpClient client = HttpClient.newHttpClient();
// asynchronous
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())

// synchronization
HttpResponse<String> response = client.send(request, 

On the optimization of the bottom layer

  • Scalable low latency garbage collector ZGC (although it is an experimental stage, it can be regarded as the most important feature of Java 11)
  • Nested based access control

Java 12

switch expression syntax

Originally, the switch always needed to use break to isolate each case. After Java 12, it was implemented through case L - > to achieve isolation. It also supports the return value, which can be assigned.

String season = switch (day) {
    case "march", "april", "may"            -> "spring";
    case "june", "july", "august"           -> "summer";
    case "september", "october", "november" -> "autumn";
    case "december", "january", "february"  -> "winter";
    default -> {
        break "unknown";

Java 13

Text block

The text block is still a preview function, which is convenient for creating multi line strings
In the past, a long string constant was declared in the code, and the + connection was used through line feed.

String html ="<html>\n" +
			  "   <body>\n" +
			  "      <p>Hello, World</p>\n" +
			  "   </body>\n" +

In the form of text blocks, for example:

String html =  """
                       <p>Hello, World</p>

Java 14

instanceof type judgment

At present, it is still a preview function, which is used to automatically convert the type after using instanceof to determine the type.

// Before java14
if (obj instanceof String) {
	String str = (String) obj;

// After java14
if (obj instanceof String str) {

Packaging tools

Java 14 introduces a packaging tool. The command is jpackage. Using jpackage command, JAR packages can be packaged into software formats supported by different operating systems.

The main platform formats are as follows:

  • Linux: deb and rpm
  • macOS: pkg and dmg
  • Windows: msi and exe

NullPointerException optimization prompt

The original null pointer exception can only be reported until the first row, and the specific field in this row cannot be determined. The null pointer in Java 14 clearly indicates the specific field.

Exception in thread "main" java.lang.NullPointerException: 
	Cannot invoke "String.length()" because "test" is null

Record class

Record is a new type, a restricted form similar to enumeration. It is essentially a final class.

// definition
public record Person(String name, String gender) {

// use
Person tom = new Person("Tom", "male");
Person june = new Person("June", "female");

Java 15

Hidden class

This allows developers to introduce classes that cannot be found and used elsewhere and have a limited life cycle. This is very beneficial to the use of dynamically generated classes (reflection) at run time, and can reduce memory consumption. It should be more suitable for framework development.

Sealing class

The preview feature is also available in Java 15. A sealed class is used to control the subclasses that are allowed to inherit from it. It is not possible for any subclass to inherit if it wants to

public sealed interface Animal permits Dog, Cat {

Disable and cancel bias lock

One of the lock inflation mechanisms during synchronized synchronization is biased locking. The introduction of this mechanism increases the complexity of the JVM, but the performance improvement is general, so it is disabled by default.

ZGC officially released

ZGC, as an extensible low latency garbage collector, was officially put into use in Java 15 after the introduction of Java 11.

Java 16

Java 16 has many new features in syntax, mainly the preview features introduced in previous versions have been officially released. For example, the packaging tool, instanceof and Record classes in Java 14

Java 17

Java 17 was officially released on September 14, 2021. Java 17 is an LTS version.

Restore strict floating point semantics

Java 1.2 introduces Java's change to the default floating-point semantics to improve JVM performance at the expense of a little floating-point precision, and introduces strictfp to manually enable strict floating-point semantics. Java 17 restores strict floating point semantics as the default semantics.

Delete Applet

Applet is a small application written in Java that can be embedded into HTML. The embedding method is through the ordinary HTML tag syntax. Because it is already outdated, there are almost no scenes in use, and it is completely deleted in Java17.

switch type match

Preview properties. Like instanceof, switch adds the automatic conversion function of type matching

static String test(Object o) {
    return switch (o) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> o.toString();

Other features are briefly listed as follows:

  • Enhanced pseudorandom number generator
  • Seal class officially released


You can see that the fast iterative version of Java refers to the syntax design of other languages and class libraries, which brings a lot of syntax sugar. With the rapid release cycle every six months, more changes are introduced, and it is more important to keep an eye on the changes of the Java platform. At present, Lambda in Java has little support for functional expression. We look forward to this enhancement in subsequent updates.

Keywords: Java Back-end JavaSE

Added by fazbob on Mon, 10 Jan 2022 06:10:50 +0200