How to create records in Java 17 for immutable data models

In Java 17, you can use the record feature to create immutable data models. Records are a new type of class in Java designed specifically to hold immutable data. Using records simplifies creating classes that are essentially data carriers. Here’s a step-by-step guide on how to create and use records in Java 17:

What is a Record?

A record is a special kind of class in Java introduced in Java 14 (as a preview) and became stable in Java 16+. It:

  • Is designed for immutability
  • Automatically generates boilerplate code like getters, equals(), hashCode(), and toString()

Syntax of a Record

Declaring a record is simple. Here’s the syntax:

public record RecordName(datatype field1, datatype field2, ...) {}

Key Features of Records

  1. Records automatically:
    • Generate getter methods for fields (no need for get prefix – field name itself is used).
    • Override toString(), hashCode(), and equals().
  2. Records are immutable (fields cannot be changed after initialization).

  3. Records can include custom methods.
  4. Records cannot extend other classes (inheritance is not allowed) but can implement interfaces.

An Example: Immutable Data Model with Records

package org.kodejava.basic;

public record Person(String name, int age) {
    // Custom constructor (optional)
    public Person {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
    }

    // Example of adding a custom method
    public String greet() {
        return "Hello, my name is " + name + " and I am " + age + " years old.";
    }
}

How to Use Records

You use a record just like any other class:

package org.kodejava.basic;

public class Main {
    public static void main(String[] args) {
        // Create a record instance
        Person person = new Person("John Doe", 30);

        // Access fields using getters
        System.out.println("Name: " + person.name());
        System.out.println("Age: " + person.age());

        // Use a custom method
        System.out.println(person.greet());

        // Immutability tested
        // person.name = "New Name"; // Compilation error because fields are final
    }
}

Output:

Name: John Doe
Age: 30
Hello, my name is John Doe and I am 30 years old.

Advantages of Using Records

  1. Less Boilerplate Code: You don’t need to write getters, setters, constructors, or methods like toString() and hashCode().
  2. Thread-Safety: Records are immutable, making them easy to use in concurrent environments.
  3. Better Readability: The succinct syntax improves code readability.

Restrictions of Records

  1. Records are final — you cannot extend them.
  2. Fields in a record are also final and cannot be changed.
  3. Records themselves cannot be mutable.

When Should You Use Records?

You should use records when:

  • You need a simple data model to hold immutable data.
  • You want to avoid the verbosity of writing boilerplate code for fields and methods (getters, toString(), etc.).

For mutable data, traditional classes or other patterns should be used instead of records.

Leave a Reply

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