DEV Community

Cover image for What is Record in Java? What problem does it solve?
Pradipta
Pradipta

Posted on

3 2

What is Record in Java? What problem does it solve?

For any data intensive applications, we write Java classes that can hold the data as per our requirement.

We need to define the following in most cases :

  • Define the variables

  • Define the constructor

  • Define the getter and setter methods

  • Override equals() and hashCode() methods

  • Override the toString() method

Although some of these can be auto-generated from IDEs, but lines of code increases with the increasing number of data elements.

Record comes to the rescue and reduces all the boilerplate code we had to write thus far. Record was introduced in Java language as a preview feature in Java SE 14.

How to define a record?

public record EmployeeRecord(String name, int employeeNumber) {
}
Enter fullscreen mode Exit fullscreen mode

Records can be instantiated like a class and attributes can be accessed by getter methods[please note that the the getter method names do not start with getXXXX()]

public class RecordExampleTest {
    public static void main(String[] args) {
        EmployeeRecord employeeRecord = new EmployeeRecord("Pradipta", 123);
        System.out.println(String.format("Employee Name : %s , Employee Number : %s",
                employeeRecord.name(), employeeRecord.employeeNumber()));
    }
}
Enter fullscreen mode Exit fullscreen mode

Constructor gets automatically generated which is known as Cannonical Constructor. The methods like toString(), equals() and hashCode() methods are also automatically generated implicitly.

Some points to remember :

  • Instance methods and static methods can be created inside a Record.

  • Static fields can be declared inside a Record.

  • Instance fields cannot be declared inside a Record.

  • Records cannot extend any other class as it implicitly extends Record class. As Java does not support Multiple Inheritance, Records cannot extend any other class.

  • Records are implicitly final - they cannot be extended by any other classes.

  • Records can implement interfaces.

  • Although Records provide Cannonical constructor by default, custom constructors can be created as well. It is not necessary to mention the arguments and set them explicitly if all the arguments to be set as mentioned in the Record. This is also known as Compact Constructor. Compact Constructors may be useful if some custom logic needs to be implemented.

The points mentioned above can be represented like below :

public record EmployeeRecord(String name, int employeeNumber) {
    private static final String DEFAULT_VALUE = "default-value";

    public EmployeeRecord {
        if(employeeNumber < 0)
            throw new IllegalStateException("Employee Numbers cannot be negative");
    }
    public String generateUniqueNumber() {
        return name + "-" + employeeNumber;
    }

    public static void printSomething() {
        System.out.println("Print anything here...." + DEFAULT_VALUE);
    }
}
Enter fullscreen mode Exit fullscreen mode

Billboard image

Use Playwright to test. Use Playwright to monitor.

Join Vercel, CrowdStrike, and thousands of other teams that run end-to-end monitors on Checkly's programmable monitoring platform.

Get started now!

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay