Ch. 7 · Java

Java Records and Shallow Immutability

Java Records and Shallow Immutability. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

Records provide concise data carriers with generated component-based methods. Their component references are final, but referenced values can remain mutable.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: A record containing a list still needs a defensive-copy policy. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Inspect component types

Records make references final, not every referenced object immutable.

Step 2: Copy mutable inputs

Use the canonical or compact constructor to establish collection ownership.

Step 3: Consider nested elements

An immutable list can still hold mutable records or objects.

Worked scenario

A record containing a list still needs a defensive-copy policy.

record Config(java.util.List<String> names) {
  Config { names = java.util.List.copyOf(names); }
}
java

Strings are immutable, so this example protects both the list structure and its element values. A list of mutable customer objects would need more decisions.

Common mistake

Assuming a record recursively freezes its contents allows external mutation.

Verify the behavior

Alter the original list after construction and attempt changes through the accessor.

Interview exercise

Protect a list component.

Answer and reasoning

Copy it in the constructor and consider whether the list’s elements themselves are immutable.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc