Java Record


Java introduced a new feature called Records in Java 14, which provides a concise way to declare classes whose main purpose is to hold data. Records automatically generate constructor, accessor methods, equals(), hashCode(), and toString() methods, reducing the amount of boilerplate code required. Here’s an example of using records in Java:

public record Person(String name, int age) {
    // Optional: You can also define additional methods or constructors here
}

In this example, we define a Person record with two fields: name of type String and age of type int. The record automatically generates the constructor, accessor methods, equals(), hashCode(), and toString() methods based on the fields.

Let’s see how we can use the Person record:

Person person = new Person("John Doe", 30);

System.out.println(person.name()); // Accessing the 'name' field using the accessor method
System.out.println(person.age());  // Accessing the 'age' field using the accessor method

System.out.println(person);        // Prints the record using the automatically generated 'toString()' method

Person otherPerson = new Person("John Doe", 30);
System.out.println(person.equals(otherPerson));  // Prints 'true' as the records have the same field values

The output of the above code will be:

John Doe
30
Person[name=John Doe, age=30]
true

Records are immutable by default, meaning their fields cannot be modified once an instance is created. However, you can override this behavior by declaring a record with the mutable modifier:

public record MutablePerson(String name, int age) {
    // Additional methods or constructors can be defined here
}

Records provide a convenient way to define simple data-holding classes with minimal code. They are commonly used in scenarios where the main purpose of a class is to store data, such as representing DTOs (Data Transfer Objects), model objects, or value objects.

Note that records were introduced in Java 14 as a preview feature and became a standard feature starting from Java 16. Therefore, make sure you have the appropriate Java version installed to use records.