You are here
Home > java > Core Java >

Java 14 Features

java 14 featuresAfter 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.

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.

Record Types

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. In order to get the complete code of class Record, visit the link class Record.

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.

Declaring a 'record'
public record StudentRecord(Long rollNo, String Name, int age, String email) {

	}

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.

TestRecord
public class TestRecord {
    public static void main(String[] args) 
    {
        StudentRecord s = new StudentRecord
                (24l, "Robert", 24,"[email protected]");
         
        System.out.println(s.name());
        System.out.println(s.email());
        System.out.println(s);
    }
}

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.

Compiler Generated StudentRecord class
public final class StudentRecord extends java.lang.Record {

public StudentRecord(java.lang.Long, java.lang.String, int, java.lang.String);

	public java.lang.String toString();

	public final int hashCode();

	public final boolean equals(java.lang.Object);

	public java.lang.Long id();

	public java.lang.String name();

	public int age();

	public java.lang.String email();

}

Syntax to add a new field 

Below code snippet shows the syntax to add a new field in ‘record’

How to add new fields to 'StudentRecord'
record StudentRecord(String name){};           // adding one field
record StudentRecord(String name, int age){};  // adding two fields

 

Switch Expressions

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 arrow (->) 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.

Pattern Matching for instanceof


// Standard instanceof 
if (student instanceof EngineeringStudent) {
  EngineeringStudent es = (EngineeringStudent) student;
  System.out.println(es.getStudentName());
}
                
                  ⇓
				
//instanceof after Java 14 Pattaern Maching feature				
if (student instanceof EngineeringStudent es) {
  System.out.println(es.getStudentName());
}

 

Helpful NullPointerExceptions

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.

package com.dev.dp.srp;

public class NPETest {	
	public static void main(String[] args) {
	      Student student = null;
	      // some other logic goes here
	      // some other logic goes here
	      // some other logic goes here
	      System.out.println(student.getName());
	}
}

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)

Text Blocks

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.

Indentation

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.

//Only spaces represented by dots will be removed
       
         String text= """
...........     New Features
...........     of Java 14
...........     with Text Blocks
...........""";

Escaping

The text block allows use of the escape sequences \” and \n, but not mandatory or recommended.

   String outerText =  
    """
    String innerText = \"""
        This is an inner Text Block inside an outer Text Block
    \""";
    """;

 

Explore about Java 15 Features

close

Leave a Reply

Top