Java 14 – New Features and Improvements

Java 14 reached general availability on 17 March 2020. In this post, we will go through some features from the list of 16 new features added in Java programming language.

We can find the JDK 14 binaries here.

1. JEP 305 – Pattern Matching for instanceof (Preview)

In Java 14, instanceof operator has been modified to have type test pattern. A type test pattern (used in instanceof) consists of a predicate that specifies a type, along with a single binding variable.

In the code below, the phrase String s is the type test pattern:

if (obj instanceof String s) {
    // can use s here
} else {
    // can't use s here
}

In above example, the instanceof operator “matches” the target obj to the type test pattern if obj is an instance of String, then it is cast to String and assigned to the binding variable s.

Note that the pattern will only match, and s will only be assigned, if obj is not null.

Read More : Java – Pattern Matching for instanceof

2. JEP 368 – Text Blocks (Second Preview)

In Java, a text block is a multi-line string literal. It means we do not need to get into mess of explicit line terminators, string concatenations, and delimiters otherwise used for writing the normal string literals.

Text blocks comprise multiple lines of text and uses three double-quote characters (""") as its opening and closing delimiter.

The instance produced from a text block is of type java.lang.String with the same characteristics as a traditional double quoted string. This includes object representation and interning into string pool.

Also, Text blocks can be used anywhere a string literal can be used. For example, we can use it for string concatenation.

String string = "Hello";
String textBlock = """
                    World""";
 
String joinedString =  string + textBlock;
 
System.out.println(joinedString);

Read More : Java – Text blocks

3. JEP 358 – Helpful NullPointerExceptions

Java 14 improves the usability of NullPointerException generated by the JVM by describing precisely which variable was null.

First, we need to pass -XX:+ShowCodeDetailsInExceptionMessages JVM flag to enable this feature while running the application. Make sure, you are passing it.

public class HelpfulNullPointerException 
{
    public static void main(String[] args) 
    {
        Employee e = null;
         
        System.out.println(e.getName());
    }
}
Exception in thread "main" java.lang.NullPointerException: 
    Cannot invoke "com.howtodoinjava.core.basic.Employee.getName()" because "e" is null
    at com.howtodoinjava.core.basic.HelpfulNullPointerException.main 
    (HelpfulNullPointerException.java:9)

Only NPEs that are created and thrown directly by the JVM will include the null-detail message (messages we generally pass in the constructor when we create the exception in the program). NPEs that are explicitly created and/or explicitly thrown by programs running on the JVM are not subject to the bytecode analysis.

Read More : Java 14 – Helpful NullPointerException

4. JEP 359 – Records (Preview)

record type has been introduced as preview feature in Java 14 and shall be used as plain immutable data classes for data transfer between classes and applications.

Like enum, record is also a special class type in Java. It is intended to be used in places where a class is created only to act as plain data carrier.

The important difference between class and record is that a record aims to eliminate all the boilerplate code needed to set and get the data from instance. Records transfer this responsibility to java compiler which generates the constructor, field getters, hashCode() and equals() as well toString() methods.

public record EmployeeRecord(Long id, 
        String firstName, 
        String lastName, 
        String email, 
        int age) {
     
}

Read More : Java 14 – record type

5. JEP 361 – Switch Expressions (Standard)

A switch statement allows the application to have multiple possible execution paths based on the value of a given expression in runtime.

In Java 14, with switch expression, the entire switch block “gets a value” that can then be assigned to a variable in same statement.

It has the support of multiple case labels and using yield to return value in place of old return keyword.

In case of enum, we can skip the default case. If there is any missing value not handled in cases, compiler will complain. In all other expression types (int, strings etc), we must provide default case as well.

public static Boolean isWeekDay (Day day) 
{
    Boolean result = switch(day) {
        case MON, TUE, WED, THUR, FRI ->
        { 
            System.out.println("It is WeekDay");
            yield true; 
        }
        case SAT, SUN ->
        { 
            System.out.println("It is Weekend");
            yield false; 
        }
    };
    return result;
}

Read More : Java 14 – switch expression

6. More Features

6.1. JEP 343 – Packaging Tool (Incubator)

With JDK 8, a tool called javapackager was released as part of the JavaFX kit. However, after JavaFX split from Java with the release of JDK 11, the popular javapackager was no longer available.

This JEP create a simple packaging tool, based on the javapackager tool which supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.

The tool can be invoked directly, from the command line, or programmatically, via the ToolProvider API.

$ jpackage --name myapp --input lib --main-jar main.jar

6.2. JEP 345 – NUMA-Aware Memory Allocation for G1

In Numa (Non-Uniform Memory Access) memory architecture, each processor core receives a small amount of local memory, but the other cores are granted access to it.

The parallel garbage collector, enabled by -XX:+UseParallelGC, has been NUMA-aware for many years and has improving the performance of configurations that run a single JVM across multiple sockets.

With this JEP, G1 garbage collector has been enhanced for better memory management under Linux OS.

6.3. JEP 349 – JFR Event Streaming

This JEP exposes JDK Flight Recorder data for continuous monitoring, both for in-process and out-of-process applications.

To consume the data today, a user must start a recording, stop it, dump the contents to disk and then parse the recording file. This works well for application profiling, where typically at least a minute of data is being recorded at a time, but not for monitoring purposes.

The package jdk.jfr.consumer, in module jdk.jfr, is extended with functionality to subscribe to events asynchronously. Users can read recording data directly, or stream, from the disk repository without dumping a recording file.

6.4. JEP 352 – Non-Volatile Mapped Byte Buffers

This JEP adds a new JDK-specific file mapping modes so that the FileChannel API can be used to create MappedByteBuffer instances that refer to NVM (non-volatile memory). NVM is also known as persistent memory and is used to store data permanently.

Recent changes to the MappedByteBufer API mean that it supports all the behaviours needed to allow direct memory updates and provide the durability guarantees needed for higher level, Java client libraries to implement persistent data types (e.g. block file systems, journaled logs, persistent objects, etc.).

6.5. JEP 363 – Remove the Concurrent Mark Sweep (CMS) Garbage Collector

This JEP aims to remove the CMS garbage collector after it was marked as deprecated in Java 9 (JEP 291). Interested users had two years to take care of the project and maintain it but it didn’t happened.

So now, CMS GC has been removed from Java 14. Note that CMS garbage collector has not been removed from prior releases and will be available till Java 13.

6.6. JEP 367 – Remove the Pack200 Tools and API

Remove the pack200 and unpack200 tools, and the Pack200 API (compression scheme for JAR files introduced in Java SE 5.0) in the java.util.jar package. These tools and API were deprecated for removal in Java SE 11 with the express intent to remove them in a future release.

6.7. JEP 370 – Foreign-Memory Access API (Incubator)

With this JEP, Java provides an API to allow Java programs to safely and efficiently access foreign memory outside of the Java heap.

Thegoal is that the same API should be able to operate on various kinds of foreign memory (e.g., native memory, persistent memory, managed heap memory, etc.).

It should not be possible for the API to undermine the safety of the JVM, regardless of the kind of memory being operated upon. Also, memory deallocation operations should be explicit in the source code.

Drop me your questions in comments related to Java 14 new features.

Happy Learning !!

Reference : Java 14 Release

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.