After the release of Java 13 on 17 September, 2019 and completing the six-month cycle, Java 14 version was released on 17 March 2020. We can download Java 14 from here. Here we will talk about Java 14 Features.
Some of the features in Java 14 are in ‘Preview’ Stage, while others finalized by Oracle community. One of the popular feature ‘Switch Expressions’ which was a Preview feature is now approved in Java 14. We will discuss in detail about all of them in this article.
Table of Contents (Click on links below to navigate)
Java 14 Features
As a developer, we have following new features which are added in Java 14.
1. Record Type (Preview)
2. Switch Expressions
3. Pattern matching for instanceof Operator (Preview)
4. Helpful NullPointerExceptions
5. Text Blocks (Preview)
What is a Preview feature in Java?
A preview language feature is a newly added feature of the Java SE Platform that is fully specified, fully implemented, and yet not a permanent feature. It is available in a JDK feature release as a trial to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform based on the feedback. Preview features may be removed in a future release, or upgraded to permanent features of the Java language.
The new keyword ‘record’ is a special class type in java like enum. So it is known as record type. In other words, Records are a new kind of type declaration in the Java language. It is introduced in Java 14 as a preview feature. A record is a data class that will store data. It will help to reduce boilerplate code & create simple, concise classes immediately. The primary idea behind introducing the type record is to use record type instead of a normal class type where a normal class is created only to act as a simple data carrier. Record is an abstract class under java.lang package and it extends from java.lang.Object class. Complete code of class Record can be found here.
Records eliminate the boilerplate code by transferring this responsibility to java compiler which generates the constructor, getter methods of declared fields, hasCode(), equals(), and toString() as well.
Syntax to declare a ‘record’
The syntax is similar to declaration of a parameterized constructor in java using keyword record as shown in below code snippet.
In the above example, StudentRecord contains the information of a Student.
Creating & testing a ‘record’
Like creating object of a class, calling its constructor and passing all the field information in it will create the record. Then we can retrieve the record information using compiler generated getter methods as below.
While creating StudentRecord record, the compiler includes following things in generated .class file. Hence eliminates boilerplate code.
A constructor with all declared fields.
The equals() and hashCode() methods.
The toString() method for printing the values of all fields in the record as usual.
The getter methods similar to field names i.e. id(), name(), age() and email(). It doesn’t prefix ‘get’ into it.
It does not generate any setter method that indicates a record instance is immutable.
The class extends java.lang.Record by default, which is the base class for all records. Hence a record cannot extend any other class.
The class is final, so we cannot create a subclass of it.
If you decompile the .class file, you will see the following auto-generate code.
Syntax to add a new field
Below code snippet shows the syntax to add a new field in ‘record’
In Java 12 & Java 13 it was added as a preview feature. Now in Java 14 it is as an approved feature. It supports multiple case labels and use yield to return value in place of old return keyword. Apart from that it supports returning value via label rules ie. arrow operator similar to lambda expressions.
When we use arraw (->) operator, we can skip yield keyword.
When we use colon (:) operator, we need to use yield keyword.
In case of multiple statements, we use curly braces along with yield keyword.
Pattern matching for instanceof Operator
This feature is a preview feature in Java 14. The instanceof keyword also known as type comparison operator because it compares the instance with type. If we need to test if an object (instance) is a subtype of a given type, we use instanceof operator. It returns either true or false, returns true if the left side of the expression is an instance of the class name on the right side. The instanceof evaluates to true if an object belongs to a specified class or its super class; else raises compilation error. For example, a Student can be of type MedicalStudent or EngineeringStudent. Based on the required context we can use the instanceof operator here. Standard instanceof condition always has typecasting statement in the next line.
New feature eliminates the typecasting statement and we can use the instance directly based on the pattern matching as shown in the below code snippet.
This features is new in Java 14 Features list. Sometimes finding NullPointerException becomes difficult as Java stack trace only shows the line number where the NPE exists, but it doesn’t show the name of object whose value is null. In this case we manually figure out the object whose value is null. After introduction of this new feature compiler will show the exact object name whose value is null but we have do some setting before making use of the new feature. For that we have to set VM option -XX:+ShowCodeDetailsInExceptionMessages which enables the new feature as by default it is disabled. Suppose we have a class NPETest as in below code snippet.
If we run above code, we will get following massage in Java 13 or before versions.
Exception in thread "main" java.lang.NullPointerException at com.dev.dp.srp.NPETest.main(Test.java:7)
If we run above code in Java 14, we will get the following message:
java.lang.NullPointerException: Cannot invoke "com.dev.dp.srp.NPETest.getName()" because "student" is null at com.dev.dp.srp.NPETest.main(Test.java:7)
A Text block is a multi-line string literal. It avoids the need of most escape sequences, automatically formats the string in a predictable way, making inline multi-line Strings more readable and gives the developer control over the format when desired. The first preview of Text Blocks was introduced in Java 13 as a new, more concrete and concise vision for how Raw String Literals should work in Java. You can read more about the withdraw of JEP 326 here.
To remove white spaces from every line, the compiler determines the line with the least white space characters and then shifts the complete text block to the left. The compiler takes white space indentation into consideration, differentiating incidental white spaces from essential white spaces.
The text block allows use of the escape sequences \” and \n, but not mandatory or recommended.