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()
, andtoString()
Syntax of a Record
Declaring a record is simple. Here’s the syntax:
public record RecordName(datatype field1, datatype field2, ...) {}
Key Features of Records
- Records automatically:
- Generate
getter
methods for fields (no need forget
prefix – field name itself is used). - Override
toString()
,hashCode()
, andequals()
.
- Generate
- Records are immutable (fields cannot be changed after initialization).
- Records can include custom methods.
- 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
- Less Boilerplate Code: You don’t need to write getters, setters, constructors, or methods like
toString()
andhashCode()
. - Thread-Safety: Records are immutable, making them easy to use in concurrent environments.
- Better Readability: The succinct syntax improves code readability.
Restrictions of Records
- Records are final — you cannot extend them.
- Fields in a record are also final and cannot be changed.
- 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.