Skip to content

Records & Ownership

The Course
•
20 min study

Build on Java intermediate: you should be comfortable with private fields, constructors, interfaces, generics, collection copies and simple tests. This week turns those tools into reliable application boundaries. Start by replacing repetitive value classes with records, without losing their validation or ownership rules.

Check your intermediate foundations

Try these before reading on: create two equal values with an immutable class, return a list snapshot that cannot change its owner, and write a rejection check that fails if invalid input is accepted. Revisit value equality, copies and ownership, or regression tests if one is uncertain.

Intermediate skillWhat advanced adds
Immutable classes and equals/hashCodeRecords that generate the routine value methods
Interfaces and enum alternativesA sealed family with different data in each alternative
A null result meaning absentAn Optional return type making absence explicit
Loops, lambdas and streamsDecimal reductions, grouping and collection choices
Recover per linePreview and stage a whole batch before committing

No prior records, pattern switches, decimal library, regex or test framework is assumed. New syntax is introduced before the project relies on it. The daily times are estimates: take two sessions for a day if the independent checkpoint needs more practice.

Understand the contract

A record declares a fixed set of components. record Task(String title, int minutes) generates a constructor, private final fields, public accessors named title() and minutes(), and value-based equals, hashCode and toString. It does not generate setters. Records are final: other classes cannot extend them. A record is useful for a value whose components describe its identity, not for every object in an application.

A compact constructor uses the record name followed by a body, without repeating parameters. Validate or normalize the component parameters there. Java assigns them to the fields after the body completes; write title = title.trim(), not an assignment to this.title. If validation throws, construction fails. The generated equality uses all components, so two normalized tasks compare equal only if both title and minutes match.

This should feel familiar from intermediate's immutable Task. The shorter declaration removes repeated plumbing, not the responsibility to decide validity. Null is not a meaningful title, and a nonpositive duration is not allowed here. The classic Main frame stays the same; no new project tooling is needed.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        Task a = new Task(" Read ", 25);
        Task b = new Task("Read", 25);
        System.out.println(a.title());
        System.out.println(a.equals(b));
        System.out.println(a.equals(new Task("Read", 10)));
    }
}

record Task(String title, int minutes) {
    Task {
        if (title == null || title.trim().isEmpty() || minutes <= 0) {
            throw new IllegalArgumentException("valid task required");
        }
        title = title.trim();
    }
}
Check your prediction
Text
Read
true
false

Trace a different case

A final reference does not freeze the object it refers to. A record containing a List needs the same defensive-copy decision you learned in intermediate. List.copyOf takes an unmodifiable shallow snapshot and rejects null elements. Strings are immutable, so sharing their references is sufficient here. With mutable elements, you would need another ownership policy. The accessor returns that snapshot; later changes to the caller's original list cannot change the record.

Compare the boundary case Java
import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Read");
        Plan plan = new Plan(source);
        source.clear();
        System.out.println(plan.titles());
        try {
            plan.titles().add("Test");
        } catch (UnsupportedOperationException expected) {
            System.out.println("Snapshot protected");
        }
    }
}

record Plan(List<String> titles) {
    Plan {
        titles = List.copyOf(titles);
    }
}
Check your prediction
Text
[Read]
Snapshot protected

Compare the record with the class it replaces

Intermediate's immutable class manually declared fields, a constructor and accessors. A record supplies those routine pieces, so review the remaining constructor body as the domain contract. What it accepts, normalizes and rejects still comes from you. Generated code cannot infer that a title must be nonblank.

Record equality includes every component. If a task's identity is an external ID independent of editable details, ask whether whole-record equality is the question you need. In the later ledger it deliberately means identical normalized request content for replay detection; the map key separately identifies the request ID.

For a record containing a collection, draw both the record's field and the caller's original reference. Only a defensive container copy separates their membership. final component references alone leave shared mutable state.

Build it yourself

Exercise

Records & Ownership: practice

Create Tag(String text) as a record. Trim text and reject null or blank text with IllegalArgumentException. Check that " Java " equals "Java", that "java" stays different, and that blanks are rejected. Print Tag checks passed only after the checks. Do not override equals merely to make a failing normalization test pass.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        // Add your implementation and checks below.
        System.out.println("Your workspace");
    }
}
Hint 1: the idea

Keep normalization in construction so every valid instance follows the same equality policy.

Hint 2: a first step

Use a compact constructor; compare whole Tag values with equals after construction.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        check("normalized", new Tag(" Java ").equals(new Tag("Java")));
        check("case matters", !new Tag("Java").equals(new Tag("java")));
        try {
            new Tag(" ");
            throw new AssertionError("blank accepted");
        } catch (IllegalArgumentException expected) {
            // Only the documented rejection is expected.
        }
        System.out.println("Tag checks passed");
    }

    static void check(String name, boolean condition) {
        if (!condition) {
            throw new AssertionError(name);
        }
    }
}

record Tag(String text) {
    Tag {
        if (text == null || text.trim().isEmpty()) {
            throw new IllegalArgumentException("text required");
        }
        text = text.trim();
    }
}

Expected output:

Text
Tag checks passed

Normalization lives in the compact constructor, so there is no way to build a Tag holding " Java "; the generated equals then compares already-trimmed text and the "normalized" check passes without overriding anything. The blank check runs on the trimmed text, so " " is rejected rather than stored as an empty tag. The "case matters" check guards against over-normalizing with toLowerCase.

Change it and test again

Remove normalization temporarily. Which equality check fails? Restore it, then remove the copy from Plan and observe how clearing source changes the record. Do not confuse a compact declaration with deep immutability. Add an empty-list Plan case; empty is valid even though null elements are not.

Explain before moving on

Explain which methods Java generated and which rules you wrote. If this lesson feels fast, revisit intermediate's constructors, equality and copies lessons before continuing. Suggested study times include practice, not just reading; split the day if you need more attempts.

Was this article helpful?

Your response is saved on this device.