Martin Ahrer

Thinking outside the box

Java 16 major language and API improvements

2024-08-25 2 min read Martin

Java ⑯ has been released in March 2021.

The following content is summarizing the most important changes to the Java API, the Java language, and the JVM introduced with Java ⑯.

For a more complete overview follow the links in the following sections referring to the official Oracle release documents.

Java 16 Language improvements

The following describes selected improvements of the Java language. See the Java 16 release notes. See Java Language Updates for Java SE 16.

With JEP 394, Pattern Matching for instanceof introduced in Java ⑭ is moving from preview state to final availability.

With JEP 395, Record introduced in Java ⑭ is moving from preview state to final availability.

Java 16 is introducing the following language enhancements as developer preview.

  • JEP 397 is continuing with Sealed Classes.

We are not diving into the details of these preview features and defer that until they are moving from preview for general availability.

Pattern Matching for instanceof

Pattern Matching For Instanceof
if (animal instanceof Bird b) {(1)
  b.fly();
} else if (animal instanceof Fish f) {
  f.swim();
} else if (animal instanceof Mammal m && m.walk()) {
  // ...
}
1Pattern matching eliminates a required type conversion (type cast).

Record

Record
record Point(int x, int y) {
}(1)(2)(3)(4)
1A record is implicitly final,
2has a canonical constructor equal to the header,
3has a toString(), equals(), and hashCode() method.
4Each member has an accessor method, e.g x() or y().
Compact Canonical Constructor
record Point(int x, int y) {
  public Point {
    if (x <= 0 || y <= 0) {
      throw new IllegalArgumentException();
    }(1)
  }
}
1The record components are automatically assigned at the end of the constructor.
Instance Method
record Point(int x, int y) {
  public Point moveBy(Point offset) {(1)
    return new Point(x + offset.x, y + offset.y);
  }
}
1A record can add instance methods

Java 16 API improvements

The following describes selected improvements of the Java API. See the Java 16 release notes.

Day Period Support

Day Period Support
var formatted = DateTimeFormatter
    .ofPattern("B", Locale.ENGLISH)
    .format(LocalTime.of(8, 0)); // "in the morning"

Stream Api

Stream.toList()
var stream = Stream.of("a", "b");
var list = stream.toList();