Introducing New Features in Java 14

Java 13 has just been made available to Java developers. Indeed, the latest version of the JDK was released in September 2019. While very few companies have already switched to Java 13 since this version will not benefit long-term support (LTS) from Oracle anyway, Java 14 is already showing up.

With the new Java release life cycle, this new version is expected to be released in March 2020. Time is running out, and that’s why Mark Reinhold, the chief architect of Java at Oracle, has just proposed the list of the 5 main elements of the JDK Enhancement Proposal (JEP) that should be embedded in Java 14.

I, therefore, propose an overview of the main features that should be part of Java 14 and therefore available to developers from March 2020.

Pattern Matching for instanceof

Offered in preview mode, this new feature aims to improve Java by providing to users pattern matching for the instanceof operator. Already present in other languages, pattern matching makes it possible to express the logic of a program in a more secure and concise way.

The pattern matching for the instanceof operator will facilitate the conditional extraction of components from objects.

In most Java programs, there are codes of this type:

if (obj instanceof Integer) {
    int intValue = (Integer) obj;
    // ... use intValue ...
}

Here, we test if the obj variable is an instance of Integer via the instanceof operator. When this is the case, it’s not possible to use obj directly as an integer since it must first be cast.

All this is not concise and isn’t really clear. In addition, the repetition of this type of construct in programs increases the risk of errors.

The pattern matching for the instanceof operator that’ll be introduced in preview in Java 14 will allow the following simplification:

if (x instanceof Integer i) {
    // ... use i as an Integer directly ...
}

On more complex examples, we understand even better the interest of what will be possible to do in Java 14:

String formatted = "unknown";
if (obj instanceof Integer i) {
    formatted = String.format("int %d", i);
}
else if (obj instanceof Byte b) {
    formatted = String.format("byte %d", b);
}
else if (obj instanceof Long l) {
    formatted = String.format("long %d", l);
}
else if (obj instanceof Double d) {
    formatted = String.format(“double %f", d);
}
else if (obj instanceof String s) {
    formatted = String.format("String %s", s);
}
// ... use formatted variable ...

The most interesting thing in this story is this pattern matching will be extended to other language constructs — in the first place, we should find the switch expression.

In Java 15, 16, or 17, it should be possible to replace the previous sequence of if/else by the following code:

String formatted =
    switch (obj) {
        case Integer i -> String.format("int %d", i); 
        case Byte b    -> String.format("byte %d", b); 
        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        -> String.format("Object %s", obj);
    };
// ... use formatted variable

Second Preview of Text Blocks

Introduced in preview mode with Java 13, text blocks return with a second preview in Java 14. The feedback from the community following the release in Java 13 has been taken into account with the addition of two new escape sequences.

The escape sequence \ explicitly eliminates the need to insert a new line character. Let’s take the example of a string split via the concatenation operator between different smaller strings:

String literal = "This is a string splitted " +
                 "in several smaller " +
                 "strings.";

With the escape sequence _\_, we could express it as follows in Java 14:

String text = """
                This is a string splitted \
                in several smaller \
                strings.\
                """;

Since character literals and traditional string literals don’t allow embedded line breaks, the escape sequence \ only applies to text blocks.

On the other hand, the new \s escape sequence will simply be translated into a simple space. This prevents the white space from being erased. Based on the escape sequence, we can build a string with the certainty each line will have the same length:

String colors = """
    red  \s
    green\s
    blue \s
    """;

This new escape sequence introduced in Java 14 will also be usable in traditional string literals.

Introduction of the Record Type

Java 14 should see the introduction in preview mode of the record type. Record objects allow a compact syntax to declare classes which are transparent holders for shallowly immutable data.

Like an enum, a record is a restricted form of a class. A record declares its representation and commits to an API that corresponds to this representation. record objects give up a freedom that Java classes benefit from: the ability to decouple the API from the representation. In return, the records offer a significant gain in terms of brevity.

A record has a name and a state description that declares its components. The presence of a body is optional. Here is the creation of a record type, Point:

record Point(int x, int y) { }

The latter being equivalent to the following class declaration:

final class Point {
    public final int x;
    public final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // state-based implementations of equals, hashCode, toString
    // nothing else
}

In order to take into account this new type in Java 14, two new methods have been added to the java.lang.Class object:

  • RecordComponent[] getRecordComponents()
  • boolean isRecord()

The goal here is to update the Java Reflection API to take records into account.

The Packaging Tool Is Finally Here

Removed at the last minute from the perimeter of Java 13, the jpackagepackaging tool should finally be made available in Java 14. Be careful, however; it’ll only be in the Incubator version.

This tool, which should allow developers to create autonomous Java applications, is based on the JavaFX javapackager packaging tool. Its main characteristics are:

  • Support for native packaging formats to provide users with a natural installation experience
  • Possibility to specify the launch parameters at the time of packaging
  • Launch via command line or program via the ToolProvider API

Deprecating the ParallelScavenge + SerialOld Garbage Collector Combination

The latest innovation expected for Java 14 is clearly not for all Java developers. Indeed, it intends to deprecate the ParallelScavenge + SerialOld garbage-collector combination. The JEP 366, which supports this evolution, makes it clear the purpose here isn’t to remove this suit but only to deprecate it.

Deprecating this combination of algorithms is due to the fact it’s rarely used while requiring considerable maintenance efforts.

Conclusion

Scheduled for March 2020, Java 14 will have relatively little impact on the daily work of Java developers. At the forefront of the new features is the pattern matching for instanceof that most developers will be eager to test. However, you’ll have to be patient before using this in production since this feature will only be in preview mode with Java 14.

The good news is that this pattern matching for instanceof only represents the first steps of a more extensive pattern matching that’ll happen within Java 15, 16, or 17. All this comes to the delight of developers, who will find significant gains in terms of their programs’ readability and their own development productivity.

Thank you for reading!

#java #java14 #programming #languages #technology

Introducing New Features in Java 14
1 Likes11.90 GEEK