Core Java

core16RecordsDemo

Path
pkg1core/core16RecordsDemo.java
Package
pkg1core
Study order
17
Run
Single-file source launch
Command
java pkg1core/core16RecordsDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core16RecordsDemo.java
1package pkg1core;2 3/*4 * core16RecordsDemo.java5 * ----------------6 * Records (Java 16+): immutable data carriers with auto-generated7 * constructor, accessors, equals, hashCode, and toString.8 *9 * EXPLANATION:10 *  - `record Point(int x, int y)` generates everything for a value object.11 *  - Compact canonical constructors let you validate/normalize.12 *  - Records are implicitly final and their components are final.13 */14import java.util.List;15import java.util.Objects;16 17public class core16RecordsDemo {18 19    record Point(int x, int y) {20        // Compact constructor: validation without re-listing params21        Point {22            if (x < 0 || y < 0) throw new IllegalArgumentException("negative coords");23        }24        // You can add extra methods25        double distanceTo(Point o) {26            return Math.hypot(x - o.x, y - o.y);27        }28        // And static factory helpers29        static Point origin() { return new Point(0, 0); }30    }31 32    record Range(int lo, int hi) {33        Range { if (lo > hi) throw new IllegalArgumentException("lo>hi"); }34        boolean contains(int v) { return v >= lo && v <= hi; }35    }36 37    public static void main(String[] args) {38        Point a = new Point(0, 0);39        Point b = new Point(3, 4);40 41        // Auto-generated accessors (no get prefix), toString, equals, hashCode42        System.out.println("a = " + a + ", b = " + b);43        System.out.println("b.x() = " + b.x() + ", b.y() = " + b.y());44        System.out.println("distance a->b = " + a.distanceTo(b));45        System.out.println("a.equals(origin)? " + a.equals(Point.origin()));46        System.out.println("hashCode equal? " + (a.hashCode() == Point.origin().hashCode()));47 48        // Records work great as immutable elements in collections49        List<Range> ranges = List.of(new Range(1, 5), new Range(10, 20));50        ranges.forEach(r -> System.out.println(r + " contains 3? " + r.contains(3)));51 52        // Validation in action53        try { new Point(-1, 0); } catch (Exception e) { System.out.println("Rejected: " + e.getMessage()); }54 55        System.out.println("Objects.equals check: " + Objects.equals(b, new Point(3, 4)));56    }57}