Java

Records — Concise Data Classes (Java 16+)

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`record` generates a constructor, accessors, `equals`, `hashCode`, and `toString` from a one-line declaration. Replaces 50 lines of POJO boilerplate. Records are implicitly final and immutable.
Java
Raw
// One line replaces a full POJO
public record User(int id, String name, String email) {}

// Compact constructor — validate or normalize
public record Money(long cents, String currency) {
    public Money {
        if (cents < 0) throw new IllegalArgumentException("cents must be >= 0");
        currency = currency.toUpperCase();   // normalization
    }

    // Static factory methods + custom instance methods are fine
    public static Money dollars(double d) { return new Money(Math.round(d * 100), "USD"); }
    public double asDecimal() { return cents / 100.0; }
}

void main() {
    var user = new User(42, "Alice", "a@x.com");
    System.out.println(user);             // User[id=42, name=Alice, email=a@x.com]
    System.out.println(user.name());      // Alice  (accessor, not getName)

    var price = Money.dollars(19.99);
    System.out.println(price);            // Money[cents=1999, currency=USD]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.