The record
keyword in Java is used to define a special kind of class called a record. Records provide a concise syntax for declaring immutable data carriers with automatically generated methods such as equals()
, hashCode()
, and toString()
, as well as accessor methods for their fields. Records were introduced in Java 14 as a preview feature and became a standard feature in Java 16.
Table of Contents
- Introduction
record
Keyword Syntax- Understanding
record
- Examples
- Basic Record
- Customizing Record Methods
- Compact Constructors
- Nested Records
- Real-World Use Case
- Conclusion
Introduction
Records are designed to model plain data aggregates with less boilerplate code compared to traditional Java classes. They automatically provide common functionalities for data classes, such as immutability, field accessors, and meaningful toString
, equals
, and hashCode
methods.
record Keyword Syntax
The syntax for defining a record is as follows:
public record RecordName(Type fieldName, Type fieldName, ...) { // optional methods and constructors }
Example:
public record Person(String name, int age) { }
Understanding record
Key Points:
- Immutable Data Class: Fields in a record are final and immutable by default.
- Automatic Methods: Records automatically generate
equals()
,hashCode()
,toString()
, and accessor methods. - Compact Syntax: Reduces boilerplate code for data classes.
- Constructors: Custom constructors can be defined for validation or other purposes.
Examples
Basic Record
A simple example demonstrating a basic record.
Example
public record Person(String name, int age) { } public class Main { public static void main(String[] args) { Person person = new Person("Alice", 30); System.out.println(person.name()); // Accessor method for name System.out.println(person.age()); // Accessor method for age System.out.println(person); // Automatically generated toString() method } }
Output:
Alice 30 Person[name=Alice, age=30]
Customizing Record Methods
You can customize the methods and add your own methods to a record.
Example
public record Person(String name, int age) { // Custom method public String greeting() { return "Hello, my name is " + name + " and I am " + age + " years old."; } // Custom constructor public Person { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } } } public class Main { public static void main(String[] args) { Person person = new Person("Alice", 30); System.out.println(person.greeting()); } }
Output:
Hello, my name is Alice and I am 30 years old.
Compact Constructors
A compact constructor is a concise way to define a canonical constructor, which allows you to perform validation or other operations on the fields.
Example
public record Person(String name, int age) { // Compact constructor public Person { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } name = name.strip(); // Modify the input parameter } } public class Main { public static void main(String[] args) { Person person = new Person("Alice ", 30); System.out.println(person); } }
Output:
Person[name=Alice, age=30]
Nested Records
Records can be nested inside other classes or records.
Example
public class Company { public record Employee(String name, String role) { } public static void main(String[] args) { Employee employee = new Employee("Bob", "Developer"); System.out.println(employee); } }
Output:
Employee[name=Bob, role=Developer]
Real-World Use Case
Data Transfer Object (DTO)
Records are ideal for representing DTOs, which are often used to transfer data between different layers of an application.
Example
public record Product(String name, double price) { } public class ProductService { public Product getProductDetails() { // In a real application, this data might come from a database return new Product("Laptop", 999.99); } public static void main(String[] args) { ProductService service = new ProductService(); Product product = service.getProductDetails(); System.out.println(product); } }
Output:
Product[name=Laptop, price=999.99]
Conclusion
The record
keyword in Java provides a concise and immutable way to define data classes. By automatically generating common methods and ensuring immutability, records reduce boilerplate code and improve code clarity. Understanding and using the record
keyword effectively is crucial for developing clean and maintainable Java applications that involve data modeling and transfer.