What is record patterns in Java?

Record patterns in Java, introduced in Java 16 as part of the preview features, provide a concise way to model immutable data. They simplify the data classes by allowing developers to define a class with fields, automatically providing methods like toString(), hashCode(), and equals(). This feature makes it easier to deconstruct data and enhances code readability.

Example of Record Patterns

// Example of a simple record in Java 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()); // Output: Alice System.out.println(person.age()); // Output: 30 } }

Java Record Patterns Immutable Data Data Classes Java 16