Java 14 – New Features and Improvements + Deprecated and Removed APIs + Example

In this article we will learn about New Features in Java 14 along with deprecated/removed features and APIs.

  • In simple words, Java 14 (Java SE 14) and its Java Development Kit 14 (JDK 14) open-source have been released on 17 March 2020 with significant number of Java Enhancement Proposals (JEPs) in version 14. (Even more JEPs from Java 12 and 13 combined in Java 14)
  • We will discuss each feature in detail with the help of example. Let’s have a summary of all the features along with version.

New Java language features since Java 8

Java Main Feature (Since Java 8)Since (Java Version)Preview / Incubation Since (Java)Example (Good References)
1. Record Type 14https://openjdk.java.net/jeps/359
2. Pattern Matching (E.g. ( if (x instanceOf String) { x is String here }) 14https://openjdk.java.net/jeps/305
3. Text Blocks 13https://openjdk.java.net/jeps/355
4. Switch Expressions (also JEP 354 in JDK 13)1412https://openjdk.java.net/jeps/354
5. New variants of exceptionally in CompletionStage class (async, componse)12 
6. String API Improvements (indent, transform)12 https://www.baeldung.com/java12-string-api
7. CompactNumberFormat12 https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html
8. String API Improvements (repeat, isBlank, strip, lines methods)11 https://www.baeldung.com/java12-string-api
9. Local-Variable Syntax for Lambda Parameters11 https://openjdk.java.net/jeps/286
10. New HTTPClient API119https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html
11. Local-Variable Type Inference10 https://openjdk.java.net/jeps/286
12. Flow API (reactive streams)9 https://dev.to/ajiteshtiwari/java-9-flow-api-4e38
13. Java Platform Module System (modules)9 https://openjdk.java.net/jeps/261
14. Convenience Factory Methods for Collections9 https://openjdk.java.net/jeps/269
15. Stream API Improvements (takeWhile, dropWhile, ofNullable, iterate with condition methods)9 https://www.javatpoint.com/java-9-stream-api-improvement
16. Multi-Resolution Image API9 https://docs.oracle.com/javase/9/docs/api/java/awt/image/MultiResolutionImage.html
17. Stack-Walking API9 https://openjdk.java.net/jeps/259
18. this.getClass().getPackageName()9 
19. Process API Updates (detailed info about processes, e.g. ID, onExit, destroy)9 https://openjdk.java.net/jeps/102
20. CompletableFuture API Ehancements (delay, timeout methods)9 https://ozenero.com/java-9-completablefuture-api-improvements-delay-timeout-support
21. Interface Private Methods9 https://www.javatpoint.com/java-9-interface-private-methods
22. Enhanced Deprecation – since and forRemoval in Deprecated annotation9 https://openjdk.java.net/jeps/277
23. Interface Default and Static Methods8 https://thebasictechinfo.com/java-8/java-8-features-examples
24. Method References8 https://thebasictechinfo.com/java-8/java-8-features-examples
25. Optional Class8 https://thebasictechinfo.com/java-8/java-8-features-examples
26. Lambda Expressions8 https://thebasictechinfo.com/java-8/java-8-features-examples
27. Functional Interfaces8 https://thebasictechinfo.com/java-8/java-8-features-examples
28. Stream API8 https://thebasictechinfo.com/java-8/java-8-features-examples
29. Effectively Final Variables8 https://jcp.org/en/jsr/detail?id=335
30. Repeating Annotations8 https://openjdk.java.net/jeps/120
31. New Date Time API8 https://jcp.org/en/jsr/detail?id=310

Deprecated and Removed Features/APIs since Java 8

S.No.Feature / APIDeprecated SinceRemoved Since
1.Solaris and SPARC Ports14 
2.ParallelScavenge + SerialOld GC Combination14 
3.CMS GC914
4.Pack200 Tools and API1114
5.Nashorn JavaScript Engine11 
6.Java FX (moved to OpenJFX) 11
7.Java EE and CORBA modules911
8.javah Native-Header Generator 10
9.jhat Heap Visualizer 9
10.Launch-Time JRE Version Selection 9
11.Rarely-Used GC Combinations89
12.Applet API9 

Download – JDK 14 Releases

We can download Java 14 from Oracle official website : https://jdk.java.net/14/

Java 14 : New Features Examples

In this section we will discuss Java 14 features in detail with the help of examples.

JEP 305 – Pattern Matching

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.

Instanceof is used to check whether the object reference is and instance of given Type or not, and return boolean flag. For example:

Example: Without Pattern Matching feature
if (obj instanceof String) {
    String str = (String) obj; // need to declare and cast again the object
    .. str.contains(..) ..
}else{
     str = ....
}
Example: With Pattern Matching feature
if (!(obj instanceof String str)) {
    .. str.contains(..) .. // no need to declare str object again with casting
} else {
    .. str....
}

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 str.

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

JEP 368 – Text Blocks

In Java 14, a text block is a multi-line string literal. It means we do not need to think about line terminators, string concatenations, and delimiters as we used to write the normal string literals in Java pervious versions.

In Java, to embed HTML, XML, SQL, or JSON snippet into a code is often hard to read and hard to keep, and to overcome this problem, Java 14 has introduced Text Block feature.

A text block contains zero or more content characters, which are enclosed by open and close delimiters

Example: Text Block

String str = "The Basic";
String textBlock = """
                    Tech Info""";
  
String concatStrings =  str + textBlock;
  
System.out.println(concatStrings);

Result (Output):

The Basic Tech Info

Example: HTML Example Without Text Block
String html = "<html>\n" +
              "    <body>\n" +
              "        <p>The Basic Tech Info</p>\n" +
              "    </body>\n" +
              "</html>\n";
Example: HTML Example With Text Block
String html = """
              <html>
                  <body>
                      <p>The Basic Tech Info</p>
                  </body>
              </html>
              """;

JEP 358 – Helpful NullPointerExceptions

This is very helpful feature for developer. In Java 14, NullPointerExceptions exception message generated by JVM improved. We will see in below working example.

Note: We need to pass -XX:+ShowCodeDetailsInExceptionMessages JVM flag to enable this feature while running the application.

Example: Helpful NullPointerExceptions (HelpfulNullPointerException.java)
public class HelpfulNullPointerException 
{
    public static void main(String[] args) 
    {
        Employee e = null;
          
        System.out.println(e.getName());
    }
}

On Console – Error message with improved detail as below.

Exception in thread "main" java.lang.NullPointerException: 
    Cannot invoke "com.the.basic.tech.info.Employee.getName()" because "e" is null
    at com.the.basic.tech.info.HelpfulNullPointerException.main 
    (HelpfulNullPointerException.java:9)

However there are some Risk. The null-detail message may contain variable names from the source code in Production. Exposing this information might be considered as security risk.

JEP 359 – Records (Preview)

This is a preview language feature in JDK 14. It is used to compact the class declaration syntax with record.

We need to write a lot of low-value, repetitive code to write a simple data carrier class responsibly: constructors, accessors, equals(), hashCode(), toString(), etc. To avoid this repetitive code, Java is planned to use record. For example:

Example: Code snapshot without using record feature
final class Scale {
    public final int x;
    public final int y;

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

    // state-based implementations of equals, hashCode, toString
    // nothing else
Example: Code snapshot using record feature
record Scale(int x, int y) { }
Limitation of using records Java 14 feature
  • Records cannot extend any other class, and cannot declare instance fields other than the private final fields which correspond to components of the state description.
  • Records are implicitly final, and cannot be abstract, such limitations underline that a record’s API is entirely defined by its state definition and can not be modified by another class or record later.
  • The components of a record are implicitly final.
What is difference between record and class in Java?

In Java 14, record eliminates all the 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.

JEP 361 – Switch Expressions (Standard)

  • Java 14 has extended switch statement, which can be used as an expression with help of arrow (->), and now we can yield to return the value.
  • It has the support of multiple case labels and using yield to return value in place of old return keyword.
  • This was a preview language feature in JDK 12 and JDK 13.
//Arrow labels
static void grade(int g) {
    System.out.println(
        switch (g) {
            case  1 -> "A";
            case  2 -> "B";
            default -> "C";
        }
    );
}
------------------------------------------
//Yielding a value - introduce a new yield
int j = switch (day) {
    case MONDAY  -> 0;
    case TUESDAY -> 1;
    default      -> {
        int d = day.toString().length();
        int result = f(d);
        yield result;
    }
};
Example: Switch Expression before Java 14
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}
Example: Switch Expression improvement in Java 14
switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

JEP 343 – Packaging Tool (Incubator)

In 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.

The jpackage tool bundles a Java application into a platform-specific package containing all the dependencies required. As a set of ordinary JAR files or as a collection of modules. The supported platform-specific package formats are:

  1. Linux: deb and rpm
  2. macOS: pkg and dmg
  3. Windows: msi and exe

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

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

JEP 345 – NUMA-Aware Memory Allocation for G1

  • Non-uniform memory access (NUMA) is a technique of configuring the cluster of microprocessor into a multiprocessing system, so that memory can be shared locally and performance can be improved.
  • If the +XX:+UseNUMA option is specified then, when the JVM is initialized, the regions will be evenly spread across the total number of available NUMA nodes.

JEP 349 – JFR Event Streaming

  • Java 14 provided an API, by which the data collected by the JDK Flight Recorder (JFR) will continuous monitor in-process and out-of-process applications.
  • 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.

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

Note: CMS GC has been removed from Java 14. It was marked as deprecated in Java 9 (JEP 291). It will be available till Java 13 only.

Reference : Java 14 Release

Drop me your questions in comments related to Java 14 new features. Keep exploring new things 🙂