Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Records

    A printed receipt: a fixed set of facts that never changes after printing. You don't need to design a receipt from scratch each time — the

    Chapter 12 of 122 min read

    The Plain Picture#

    A printed receipt: a fixed set of facts that never changes after printing. You don't need to design a receipt from scratch each time — the format is standard.

    The Real Name#

    A record (Java 16+) is a class for immutable data, written in one line. The compiler generates the private final fields, the constructor, the accessor methods, and correct equals, hashCode and toString.

    Java
    record QuizResult(String student, int points) {
        QuizResult {
            // "compact constructor": validation only
            if (points < 0) throw new IllegalArgumentException("points < 0");
        }
    
        QuizResult withBonus(int extra) {
            return new QuizResult(student, points + extra);
        } // "changes" return new records
    }
    Java
    QuizResult r1 = new QuizResult("Priya", 180);
    
    QuizResult r2 = r1.withBonus(20);
    
    System.out.println(
        r1 + " " + r2 + " " + r1.equals(new QuizResult("Priya", 180)) + " " + r2.points()
    );
    // QuizResult[student=Priya, points=180] QuizResult[student=Priya, points=200] true 200

    Notice: toString is readable, equals compares contents (so records are safe HashMap keys — Ch 8), and the accessor is points(), not getPoints().

    Use records for: API request/response data, results, DSA helper tuples like record Cell(int r, int c) {} for visited sets. Limits: fields are final (no setters), and records can't extend other classes (they can implement interfaces).

    Check yourself

    3 questions
    1

    What does the compiler generate for a record?

    Show answer

    Private final fields, a constructor, accessors, equals, hashCode, toString.

    2

    Why is record Cell(int r, int c) {} a good key for a HashSet of visited grid cells?

    Show answer

    It's immutable and has content-based equals/hashCode, so equal cells are found correctly.

    3

    What is a compact constructor for?

    Show answer

    Validating (or normalising) the arguments without repeating the field assignments.