record keyword in Java-14

Himanshu RaiHimanshu Rai
3 min read

In JDK-14, a new keyword record was introduced, this blog is an attempt to explain the use of this keyword and how it will help us programmers to write code with less boilerplate code in some cases.

Use case:

Let's say we have to create a new immutable Java class Employee, that can hold and pass our data. Now we know that in an immutable class, the fields should be final and private, it should have a public all argument constructor and there should be only getters and no setters. It should have toString(), equals() and hashCode() methods as well.

Keeping in mind the above requirements, our code will look something like this:

package org.example;

import java.util.Objects;

public class EmployeeNormal {

    private String name;
    private String lastName;

    public EmployeeNormal(String name, String lastName){
        this.name = name;
        this.lastName = lastName;
    }
    public String getName() {
        return name;
    }
    public String getLastName() {
        return lastName;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        EmployeeNormal that = (EmployeeNormal) o;
        return Objects.equals(name, that.name) &&            Objects.equals(lastName, that.lastName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, lastName);
    }

    @Override
    public String toString() {
        return "EmployeeNormal{" +
                "name='" + name + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

In the above example, we have to write everything on our own and let's say tomorrow the requirement changes and we need to add a new field in the Employee class.


To add a new field we will have to add that field, and then update the methods toString(), equals() and hashCode(). This process is a bit time taking and tedious.

So starting with JDK-14 Java has introduced the keyword record, using which we can write the above code in a simple way.

Like an enum, a record is a restricted form of a class. It’s ideal for "plain data carriers," classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors.

The above code sample can be written as:

package org.example;

public record EmployeeRecord(String name, String lastName) {

}

That's it....!!!!

We just need to use the keyword record and we have created our immutable class.

A record acquires these members automatically:

  • A private final field for each of its components

  • A public read accessor method for each component with the same name and type of the component; in this example, these methods are EmployeeRecord::name() and EmployeeRecord::lastName()

  • A public constructor whose signature is derived from the record components list. The constructor initializes each private field from the corresponding argument.

  • Implementations of the equals() and hashCode() methods, which specify that two records are equal if they are of the same type and their corresponding record components are equal

  • An implementation of the toString() method that includes the string representation of all the record's components, with their names

Driver code for the above example:

package org.example;

public class Main {
    public static void main(String[] args) {


        EmployeeRecord emp = new EmployeeRecord("Himanshu", "Rai");

        System.out.println(emp.name());
        System.out.println(emp.lastName());
        System.out.println(emp.hashCode());
        System.out.println(emp.toString());
    }
}

Note: Unlike traditional getters(), in record the getterName does not start with get and is just similar to the field name. It won't be emp.getName() but will be emp.name().

But, there are some restrictions as well on record, these are as following:

  • Records cannot extend any class

  • Records cannot be abstract; they are implicitly final

  • The components of a record are implicitly final


That's all for today. Thanks for reading this article.

0
Subscribe to my newsletter

Read articles from Himanshu Rai directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshu Rai
Himanshu Rai

I am a developer from Hyderabad India. I am new to writing blogs having started this blog in April 2023. I will be writing mostly on java, spring, spring boot as well as language agnostic topics like algorithms, DB, how things work under the hood etc.