Core Java

Record Keyword in Java

1. Introduction

This is an in-depth article related to Record Keyword in Java. In java, immutable data is passed between objects in applications. In Java 14, Record feature was introduced. Before this feature got introduced, we had to create a class with boilerplate fields and methods.

2. Record Keyword

In many scenarios in applications, data is immutable. These scenarios can be holding data for database queries, results, and service responses. In Java 14, record was introduced which is a special type of class definition. This is a quick way to create data objects or plain old java objects. They can be referred to as data transfer objects. Java 15 has a new preview feature related to records that local record classes.

2.1 Prerequisites

Java 14 is required on the Linux, windows, or mac operating systems.

2.2 Download

You can download Java 14 can be downloaded from the Oracle website

2.3 Setup

You can set up java by installing the package downloaded.

You can check the java setup by using the alternatives command mentioned above. You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:

Java Environment Setup

export JAVA_HOME=`/usr/libexec/java_home -v 14`

2.4 Purpose of Java Record

 You can create data classes in Java before Java 14 as below:

  1. private, final field for each piece of a data field
  2. getter for each field
  3. public constructor with data fields as parameters
  4. equals method that returns true for objects of the same data class
  5. hashCode method that returns the same when all fields of the data class match
  6. toString method that includes the name of the data class and the name of each data field and its corresponding value

For example, we can create a simple Customer data class with a name and address:

Customer Data Class

public class Customer {

    private final String name;
    private final String address;

    public Customer(String name, String address) {
        this.name = name;
        this.address = address;
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (!(obj instanceof Customer)) {
            return false;
        } else {
            Customer other = (Customer) obj;
            return Objects.equals(name, other.name)
              && Objects.equals(address, other.address);
        }
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }

    
   
    public String getName() { return name; }
 
    

    public String getAddress() { return address; }
}

The above code is not simple as it is used for transferring data. For each data transfer object, we need to implement constructor, equals, hashcode, toString, and getter methods. This is where the java 14 Record feature simplifies the data class definition.

This approach helps in defining the serializable data class and you can have :

  • nested classes and interfaces inside a record.
  • nested records too, which will implicitly be static.
  • a record can implement interfaces.
  • a generic record class.

2.5 Creating a Java Record

From Java 14, Records can be used and defined by the type and name of the fields. equals, hashCode, toString, and getter methods are generated by the Java compiler.

To create a Customer record, we’ll use the record keyword:

Java 14 Record

public record Customer (String name, String address) {}

The command to compile the above code is shown below:

Compilation Commands

(base) apples-MacBook-Air:record bhagvan.kommadi$ javac --enable-preview -source 14 RecordTest.java
Note: RecordTest.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
(base) apples-MacBook-Air:record bhagvan.kommadi$ java --enable-preview RecordTest
George Smith 201 Rosewood Street
(base) apples-MacBook-Air:record bhagvan.kommadi$

2.6 Customizing the Constructor for Java Record

You can customize the constructor as shown below:

Customizing Constructors

import java.util.Objects;
public record Customer(String name, String address) {
    public Customer {
        Objects.requireNonNull(name);
        Objects.requireNonNull(address);
    }

	public static void main(String[] args)
	{
	
		Customer customer = new Customer("George Smith", "201 Rosewood Street");
		System.out.println(customer.name() + " "+customer.address());
	}
}

The command to compile the above code is shown below:

Compilation Commands and Output

(base) apples-MacBook-Air:record bhagvan.kommadi$ javac --enable-preview -source 14 Customer.java
Note: Customer.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
(base) apples-MacBook-Air:record bhagvan.kommadi$ java --enable-preview Customer
George Smith 201 Rosewood Street
(base) apples-MacBook-Air:record bhagvan.kommadi$

2.7 Static Variables & Methods in Java Record

You can also include static variables and methods in our records. You can declare static variables using the same syntax as a class:

Static Variables

    
public record Customer(String name, String address) {
    public static String UNKNOWN_ADDRESS = "Unknown";
}

Similarly, You can declare static methods using the same syntax as a class:

Static Methods

public record Customer(String name, String address) {
    public static Customer unnamed(String address) {
        return new Customer("No name", address);
    }
}

You can then reference both static variables and static methods using the name of the record:

Referencing Static variables and methods

Customer.UNKNOWN_ADDRESS
Customer.unnamed("201 Rosewood Street");

2.8 Conclusion

We have looked at different scenarios where the Record feature can be used. A record is a data transfer object which is immutable.

Records can be used for :

  • Creating your own constructors.
  • Creating instance methods.
  • Creating static fields.

3. Download the Source Code

Download
You can download the full source code of this example here: Record Keyword in Java

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button