Skip to content

Latest commit

 

History

History
241 lines (169 loc) · 8.18 KB

File metadata and controls

241 lines (169 loc) · 8.18 KB
title Overview of New Features in Java 14 & 15
category Java
tag
Java New Features

Java 14

Precise Null Pointer Exception Messages

By adding -XX:+ShowCodeDetailsInExceptionMessages to the JVM parameters, you can obtain more detailed calling information in a null pointer exception, allowing for faster localization and resolution of issues.

a.b.c.i = 99; // Assume this line of code will cause a null pointer exception

Before Java 14:

Exception in thread "main" java.lang.NullPointerException
    at NullPointerExample.main(NullPointerExample.java:5)

After Java 14:

 // After adding the parameter, the exception message clearly indicates what is null
Exception in thread "main" java.lang.NullPointerException:
        Cannot read field 'c' because 'a.b' is null.
    at Prog.main(Prog.java:5)

Enhancements to switch (Official)

The switch statement introduced as a preview feature in Java 12 became official in Java 14, and no additional parameters are required to enable it; it can be used directly in JDK 14.

Java 12 introduced a similar lambda syntax block for switch expressions that does not require multiple break statements. Java 13 provided yield to return values from the block.

String result = switch (day) {
            case "M", "W", "F" -> "MWF";
            case "T", "TH", "S" -> "TTS";
            default -> {
                if(day.isEmpty())
                    yield "Please insert a valid day.";
                else
                    yield "Looks like a Sunday.";
            }

        };
System.out.println(result);

Preview Features

record Keyword

The record keyword can simplify the definition of data classes (Java classes that cannot be modified once instantiated). Classes defined with record replace class. You only need to declare properties to obtain access methods, as well as toString(), hashCode(), and equals() methods.

This is similar to defining a class using class with the lombok plugin and applying the @Getter, @ToString, @EqualsAndHashCode annotations.

/**
 * This class has two characteristics:
 * 1. All member properties are final
 * 2. All methods consist of the constructor and two member property accessors (a total of three).
 * Thus, this type of class is very suitable for declaration using record.
 */
final class Rectangle implements Shape {
    final double length;
    final double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    double length() { return length; }
    double width() { return width; }
}
/**
 * 1. Classes declared with record automatically have the three methods from the above class.
 * 2. In addition, it also comes with equals(), hashCode() methods, and toString() method.
 * 3. The toString method includes string representations of all member properties and their names.
 */
record Rectangle(float length, float width) { }

Text Blocks

In Java 14, text blocks remain a preview feature; however, it introduced two new escape characters:

  • \ : Indicates the end of a line without introducing a newline character.
  • \s : Represents a single space.
String str = "Where the heart is, there shall it also go.";

String str2 = """
        Where the heart is, \
        there shall it also go.""";
System.out.println(str2);// Where the heart is, there shall it also go.
String text = """
        java
        c++\sphp
        """;
System.out.println(text);
//Output:
java
c++ php

instanceof Enhancements

This is still a preview feature mentioned in Java 12 New Features.

Others

  • The ZGC introduced in Java 11 as the next generation GC algorithm after G1, now supports MacOS and Windows starting from Java 14 (I feel like I can finally experience the effects of ZGC in daily development tools, although G1 is quite usable).
  • The CMS (Concurrent Mark Sweep) garbage collector has been removed (mission accomplished).
  • The new jpackage tool not only packages applications into JAR files but also supports platform-specific feature packages, such as deb and rpm for Linux, and msi and exe for Windows.

Java 15

CharSequence

The CharSequence interface has added a default method isEmpty() to check if the character sequence is empty, returning true if it is.

public interface CharSequence {
  default boolean isEmpty() {
      return this.length() == 0;
  }
}

TreeMap

The TreeMap has introduced the following new methods:

  • putIfAbsent()
  • computeIfAbsent()
  • computeIfPresent()
  • compute()
  • merge()

ZGC (Official)

ZGC was in experimental stages during Java 11.

At that time, ZGC drew significant attention from Java developers, as it presented a different possibility for garbage collection.

After multiple iterations and ongoing refinements, ZGC is now available for use in Java 15!

However, G1 remains the default garbage collector. You can start ZGC with the following parameter:

java -XX:+UseZGC className

EdDSA (Digital Signature Algorithm)

A new digital signature algorithm based on the Edwards-Curve Digital Signature Algorithm (EdDSA) has been introduced, which is more secure and performs better.

Although it outperforms the existing ECDSA implementation, it does not completely replace the existing elliptic curve digital signature algorithm (ECDSA) in the JDK.

KeyPairGenerator kpg = KeyPairGenerator.getInstance("Ed25519");
KeyPair kp = kpg.generateKeyPair();

byte[] msg = "test_string".getBytes(StandardCharsets.UTF_8);

Signature sig = Signature.getInstance("Ed25519");
sig.initSign(kp.getPrivate());
sig.update(msg);
byte[] s = sig.sign();

String encodedString = Base64.getEncoder().encodeToString(s);
System.out.println(encodedString);

Output:

0Hc0lxxASZNvS52WsvnncJOH/mlFhnA8Tc6D/k5DtAX5BSsNVjtPF4R4+yMWXVjrvB2mxVXmChIbki6goFBgAg==

Text Blocks (Official)

In Java 15, text blocks have become an official feature.

Hidden Classes

Hidden classes are designed for frameworks, and they cannot be directly used by the bytecode of other classes. They can only be generated at runtime and accessed indirectly through reflection.

Preview Features

Sealed Classes

Sealed Classes is a preview feature in Java 15.

Before sealed classes, if we wanted to prevent a class from being inherited or modified in Java, we would modify the class with the final keyword. However, this method is not very flexible, as it completely blocks all inheritance and modification channels of a class.

Sealed classes allow restrictions on the classes that can inherit or implement them, so this class can only be inherited by specified classes.

// The abstract class Person only allows Employee and Manager to inherit.
public abstract sealed class Person
    permits Employee, Manager {

    //...
}

Additionally, any class extending a sealed class must itself be declared as sealed, non-sealed, or final.

public final class Employee extends Person {
}

public non-sealed class Manager extends Person {
}

If the allowed subclasses and sealed classes are in the same source file, the sealed class can omit the permits statement, and the Java compiler will retrieve the source file during compilation to add permitted subclasses to the sealed class.

instanceof Pattern Matching

Java 15 has not made adjustments to this feature and continues to be a preview feature, mainly to gather more user feedback.

In future Java versions, Java aims to further refine the new instanceof pattern matching feature.

Others

  • Nashorn JavaScript Engine Completely Removed: Nashorn, the JavaScript engine introduced in Java 8, saw enhancements in Java 9 that implemented some ES6 features. It was deprecated in Java 11 and has been completely removed in Java 15.
  • DatagramSocket API Refactoring
  • Disabled and Deprecated Biased Locking: The introduction of biased locking increased the complexity of the JVM more than the performance gains it brought. However, you can still enable biased locking using -XX:+UseBiasedLocking, but you will be notified that it is a deprecated API.
  • ……