java / intermediate
Snippet
Immutability with Records
Records are a special kind of class that acts as a transparent carrier for immutable data, automatically generating constructors, accessors, equals, and hashCode.
snippet.java
1
2
3
4
5
6
7
8
9
public record User(int id, String name) {}public class RecordDemo {public static void main(String[] args) {User user = new User(1, "Alice");System.out.println(user.name());System.out.println(user);}}
Breakdown
1
record User(int id, String name) {}
Defines a compact class with private final fields and public accessors.
2
user.name()
The auto-generated getter method for the 'name' component.