Java 15 New Features

Java 15 released on 15th Sep’2020 following the 6th-month release cycle. Java 15 continues support for various preview features in previous JDK releases; and also introduced some new features.

Let us learn about these new features in Java 15.

1. Sealed Classes and Interfaces (Preview) (JEP 360)

Prior to Java 15, there was no restriction on classes or interfaces regarding which all classes can inherit them. A public interface was available to be implemented by any class, and any public class was available to be extended by any other class – unless declared final.

Now with Java 15, a class or an interface can be declared sealed class or sealed interface using the modifier sealed. It is a preview feature in Java 15 through JEP 360.

A sealed class or interface restricts which other classes or interfaces may extend or implement them. Conceptually, it is a more declarative way than access modifiers to restrict the use of a class or interface as a parent class or as a parent interface.

The reserved keyword permits lists all the classes that can extend the sealed class directly. The listed subclasses can either be final, non-sealed, or sealed.

sealed class Account
    permits CurrentAccount, SavingAccount, LoanAccount {
}
 
final class CurrentAccount extends Account {}
non-sealed class SavingAccount extends Account {}
sealed class LoanAccount extends Account permits HomeloanAccount, AutoloanAccount {}
 
final class HomeloanAccount extends LoanAccount{}
final class AutoloanAccount extends LoanAccount{}

Read More: Sealed Classes and Interfaces

2. EdDSA Algorithm (JEP 339)

EdDSA (Edwards-Curve Digital Signature Algorithm) [RFC 8032] is another additional digital signature scheme added in Java 15 thorough JEP 339.

It provides much better performance and secure signatures in comparison to other available signature schemes.

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);

Read More: Java EdDSA (Ed25519 / Ed448) Example

3. Hidden Classes (JEP 371)

Hidden classes are different from normal Java classes. They cannot be used directly by the bytecode of other classes. Hidden classes are intended for use by frameworks that generate classes at run time and use them indirectly, via reflection.

With hidden classes, not framework developers can create non-discoverable classes which cannot be seen by the outside classes; and can be unloaded explicitly without being worrying about possible references from other classes.

JVM supports aggressive unloading of non-discoverable classes so that frameworks have the flexibility to define as many as they need.

Prior to Java 15, we could have created similar classes but with using non-recommeneded sun.misc.UnSafe API.

4. Other Enhancements

4.1. Pattern Matching for instanceof (Second Preview) (JEP 375)

JEP 375 proposes to re-preview the feature in JDK 15, with no changes relative to the preview in JDK 14, in order to gather additional feedback.

A type test pattern (used in instanceof) consists of a predicate that specifies a type, along with a single binding variable.

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

//Example

if(customer instanceof PersonalCustomer pCustomer)
{
    customerName = String.join(" ", pCustomer.getFirstName(), 
                            pCustomer.getMiddleName(), 
                            pCustomer.getLastName());
}
else if(customer instanceof BusinessCustomer bCustomer)
{
    customerName = bCustomer.getLegalName();
}

Read More: Pattern Matching for instanceof

4.2. Removed Nashorn JavaScript Engine (JEP 372)

Nashorn JavaScript script engine was first introduced in Java 8 as a replacement for the Rhino scripting engine. It got the first depreciation notice in Java 11.

With the rapid pace at which ECMAScript language constructs, along with APIs, are adapted and modified, maintaining Nashorn is becoming more challenging each day.

4.3. Reimplement the Legacy DatagramSocket API (JEP 373)

The new implementation is easy to debug and to adapt to work with virtual threads. This is currently being explored in Project Loom.

4.4. Records (Second Preview) (JEP 384)

Records are aimed for providing the classes which acts as immutable data carrier rather than having extensible behavior. Records automatically implement data-driven methods such as constructors, accessors, equals(), hashCode() and toString().

Records help in minimizing the common complaint with Java i.e. verbosity.

In the second preview, Records have some minor changes. Now fields inside a record should not be modified via reflection as it will throw IllegalAccessException.

4.5 Text Blocks (JEP 378)

Text blocks are finally a standard feature in Java 15. A text block is a multi-line string literal.

While using text blocks, we do not need to provide explicit line terminators, string concatenations, and delimiters otherwise used for writing the normal string literals.

String dbSchema =   """
            CREATE TABLE 'TEST'.'EMPLOYEE'
            (
              'ID' INT NOT NULL DEFAULT 0 ,
              'FIRST_NAME' VARCHAR(100) NOT NULL ,
              'LAST_NAME' VARCHAR(100) NULL ,
              'STAT_CD' TINYINT NOT NULL DEFAULT 0
            );
                    """;

Read More : Text blocks

4.6. Garbage Collection (JEP 377 and 379)

Since Java 15, ZGC (JEP 377) and Shenandoah (JEP 379) are no longer the experimental features. The default GC remains G1.

5. Conclusion

Java 15 provides new features such as sealed classes and hidden classes, as well as provides continued support to several features of past releases, including records, text blocks, new garbage collection algorithms, and more.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode