New in Java 14

29.03.2020Tom Trapp
Tech Java JVM Good-to-know

And again half a year is over and a new major JDK version, namely JDK 14 is on the way.

What’s new, what has been replaced, changed or removed? Let’s find out!

Pattern matching instanceof

The first new feature is the pattern matching for the instanceof functionality.

At first glance, you might think it’s a pattern matching like in a regex. In fact, with pattern matching redundant type castings can be avoided with a single-line expression.

The traditional way of adding this feature would be like this:

1
2
3
4
5
boolean isObjectNullOrEmpty(Object obj){
        return obj==null||
        (obj instanceof Collection&&((Collection)obj).isEmpty())||
        (obj instanceof String&&((String)obj).isBlank());
        }

This is a simple method isObjectNullOrEmpty() which checks whether an object, which can be String or Collection, is null or empty. Wouldn’t it be nice if you could assign the instanceof test object to an inline variable? This is exactly what works now:

1
2
3
4
5
boolean isNullOrEmpty(Object obj){
        return o==null||
        (obj instanceof Collection c&&c.isEmpty())||
        (obj instanceof String s&&s.isBlank());
        }

We assign the object to the variable c if it is a Collection and then carry out checks directly on this object that has already been correctly cast. Of course, this method is null-safe because we use a locial and operator and thus the right side expression is only executed if the first expression returns (left side) true.

Helpful NullPointerExceptions

The next new feature, which is currently only in the preview state, are helpful NullPointerException.

As a Java developer, for better or worse, it is very important to check for null references to avoid errors. Nonetheless, you probably know that null checks are occasionally missing and that a NullPointerException occurs. Before the release of JDK 14, it was sometimes quite difficult to find out exactly where the error came from and which variable is exactly zero, especially when there are several expressions on one line. This new feature can be activated with the following Java option:

1
XX:+ShowCodeDetailsInExceptionMessages

For example, the following code would give more detailed information about the NullPointerException:

1
2
3
4
women.partner().firstName()

        java.lang.NullPointerException:Cannot invoke"Human.firstName()"because the return
        value of"Human.partner()"is null

This clearly shows that the value of the method call Human.partner returns null.

New data type - records

A new data type with Java 14? You read that right! There is a new so-called record, at first glance this type is astonishingly similar to a Kotlin data class.

In the past, Java applications always had tons of data classes, so-called P lain O ld J ava O bjects. These pojos mostly contained simple getter & setter methods or even Lombok annotations. The record type should replace these pojos, as it provides a compact syntax for defining such data classes. For example, the Human class from the previous example would look like this:

1
2
public record Human(String firstName, String lastName, Person partner) {
}

And that’s all it takes!

The compiler generates an immutable (!) class with the constructor, the final instance variables with the appropriate Accessor Methods (leider keinen Getter Methods) and the methods hashcode, equals and toString.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public final class Human extends Record {
    private final String firstName;
    private final String lastName;
    private final Person partner;

    public Person(String firstName, String lastName, Person partner) {
        this.fristName = fristName;
        this.lastName = lastName;
        this.partner = partner;
    }

    public String toString() { /* ... */ }

    public final int hashCode() { /* ... */ }

    public final boolean equals(Object o) { /* ... */ }

    public String firstName() {
        return this.firstName;
    }

    public String lastName() {
        return this.lastName;
    }

    public Person partner() {
        return partner;
    }
}

Of course, the record type can be extended to include other static fields, methods or another constructor.

Unfortunately this is not a typical Java Bean, since the class is immutable and does not contain any getter methods. The values can no longer be changed after the object has been initialized and existing data classes have to be migrated at great expense (adopt Getter -> Accessor Methods, adopt business logic because the fields are final).

Text Blocks

If you’ve followed the last major Java versions more closely, you’re probably wondering what’s new with the Text Blocks feature. This feature is, so to speak, the successor to Raw String Literals and allows the developer to define multi-time Strings in a structured manner.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Without Text Blocks
String html="<html>\n"+
        "    <body>\n"+
        "        <p>Hello, old way</p>\n"+
        "    </body>\n"+
        "</html>\n";

// With Text Blocks
        String html="""
              <html>
                 <body>
                    <p>Hello, new way with Text Blocks</p>
                 </body>
              </html>""";

In addition, in Java 14 an old friend was introduced as Escape Sequence, the famous backslash. Strings can now be declared on several lines without unnecessary line breaks in the output.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Without Text Blocks
String literal="Lorem ipsum dolor sit amet, consectetur adipiscing "+
        "elit, sed do eiusmod tempor incididunt ut labore "+
        "et dolore magna aliqua.";

//With Text Blocks
        String text="""
                Lorem ipsum dolor sit amet, consectetur adipiscing \
                elit, sed do eiusmod tempor incididunt ut labore \
                et dolore magna aliqua.\
                """;

What else?

If you only look at the pure syntax of the programming language, that’s more or less everything that Java 14 was changed or presented to me.

Of course, a lot has changed on “under the hood” with Java 14, here are the most important changes:

  • The FileChannel API has been extended to be able to work with the MappedByteBuffer. This is currently only possible on GNU / Linux.
  • The Concurrent Mark Sweep (CMS) Garbage Collector has been completely removed, the ZGC is now available on Windows and macOS.

With the new six-month release cycle, Java is relying on a slightly different concept. Features are available earlier than preview features, can be tested and feedback from the community can be better incorporated. So the features can grow until the next Long Term Version, which will probably be Java 17 (fall 2021).

Visit us regularly to be informed about the latest changes!


This text was automatically translated with our golang markdown translator.

Tom Trapp

Tom Trapp – Problemlöser, Innovator, Sportler. Am liebsten feilt Tom den ganzen Tag an der moderner Software und legt viel Wert auf objektiv sauberen, leanen Code.