Java Records Cheat Sheet
Covers Java record syntax, compact constructors, added methods, record pattern matching, and key immutability rules for data carriers.
2 PagesIntermediateApr 2, 2026
Declaring a Record
A record is an immutable data carrier with auto-generated boilerplate.
java
// Implicitly final, implements equals(), hashCode(), toString(), and accessorspublic record Point(int x, int y) {}Point p = new Point(3, 4);System.out.println(p.x()); // 3 (accessor, not getX())System.out.println(p); // Point[x=3, y=4]System.out.println(p.equals(new Point(3, 4))); // true
Compact Constructor
Validate or normalize fields without repeating the parameter list.
java
public record Range(int min, int max) { // Compact constructor: no parameter list, fields are implicitly assigned after public Range { if (min > max) { throw new IllegalArgumentException("min must be <= max"); } }}new Range(5, 1); // throws IllegalArgumentException
Adding Methods & Static Members
Records can declare extra instance methods, static fields, and static factories.
java
public record Point(int x, int y) { static final Point ORIGIN = new Point(0, 0); double distanceToOrigin() { return Math.sqrt(x * x + y * y); } static Point of(int x, int y) { return new Point(x, y); }}
Record Patterns (Java 21+)
Deconstruct records in switch and instanceof for concise pattern matching.
java
Object obj = new Point(1, 2);if (obj instanceof Point(int x, int y)) { System.out.println(x + y);}String label = switch (obj) { case Point(int x, int y) when x == 0 && y == 0 -> "origin"; case Point(int x, int y) -> "point at " + x + "," + y; default -> "unknown";};
Key Facts
Rules and restrictions that define record behavior.
- Immutability- All fields are implicitly private and final; no setters are generated.
- Canonical Constructor- Auto-generated constructor matching the component list unless a compact or explicit one is defined.
- Accessors- Generated accessor methods are named after the field, not getX() - e.g. x() not getX().
- No Extra Instance Fields- Records cannot declare additional non-static instance fields beyond their components.
- Implicit final- A record class is implicitly final and cannot be extended.
- Can Implement Interfaces- Records can implement interfaces but cannot extend another class (they implicitly extend java.lang.Record).
Pro Tip
Use records for DTOs and immutable value objects, but keep JPA/Hibernate entities as regular classes - records' lack of a mutable state and final fields conflicts with how JPA proxies and lazy loading work.
Was this cheat sheet helpful?
Explore Topics
#JavaRecords#JavaRecordsCheatSheet#Programming#Intermediate#DeclaringARecord#CompactConstructor#Adding#Methods#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance