Lesson 22: Records (Java 16+)
23 Jul 2026 1 min Swarnil Singhai
Records are compact, immutable data carriers — the compiler auto-generates constructor, getters, equals, hashCode, and toString.
Real-time example
An API response for GeoPoint(lat, lng) needs no boilerplate — one line replaces what used to be 30+ lines of a POJO.
record GeoPoint(double lat, double lng) {}
GeoPoint delhi = new GeoPoint(28.6139, 77.2090);
System.out.println(delhi.lat()); // 28.6139
System.out.println(delhi); // GeoPoint[lat=28.6139, lng=77.209]
What's happening
Records are implicitly final and immutable — once created, delhi can never change, which is ideal for value objects like coordinates.
Use records for pure data (DTOs, API payloads, coordinates); use classes when you need mutable state or inheritance.
Advertisement