Java 16 Feature : Records

Java 16 Feature : Records

In this article, we will discuss Java 16's newest feature, Records.

Introduction

On march 16th, 2021 oracle release JDK 16 with new features . Highlights of the latest upgrade of standard Java include primitive classes, sealed classes, records, a vector API, and ports for Windows on ARM64 and Alpine Linux.

features_in_java16.png

But Record features is definitely more powerful features in JDK 16. so let's deep drive into Java Records.

what are Records?

first introduced as a preview feature in Java 14 and again in Java 15, Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data. This will significantly reduce the verbosity of these classes and improve code readability and maintainability.

purpose

Commonly, we write classes to simply hold data, such as database results, query results, or information from a service. For example, we can create a simple Person data class, with a name and an address:
public class Person {

    private final String name;
    private final String address;

    public Person(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 Person)) {
            return false;
        } else {
            Person other = (Person) obj;
            return Objects.equals(name, other.name)
              && Objects.equals(address, other.address);
        }
    }

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

    // standard getters
}

Properly writing such a data-carrier class involves a lot of boilerplate, low-value, repetitive, error-prone code: constructors, accessors, equals, hashCode, toString, etc.

As of JDK 16, we can replace our repetitious data classes with records. Records are immutable data classes that require only the type and name of fields.

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

equals, hashCode, and toString methods, as well as the private, final fields, and public constructor, are generated by the Java compiler.

Conclusion

In this blog we learned how Java Records reduce boilerplate code and improve the reliability of our immutable classes.

s960_thank_you_sticky_note.jpg