Immutable value objects
What you will learn
An immutable object cannot change its observable value after successful construction. A value object represents a value, such as a grid location, rather than an identity that changes over time. Immutability requires careful control of mutable references as well as final fields.
After this lesson you can:
- Build an immutable value object with value-based equality.
- Prevent mutable array aliases from changing an immutable snapshot.
Use a separate Main.java for each example. Compile with javac Main.java and run with java Main. The code is compatible with Java 21; Java 25 execution is not yet verified.
final class GridCell { private final int row; private final int column; GridCell(int row, int column) { if (row < 0 || row > 999 || column < 0 || column > 999) throw new IllegalArgumentException("cell outside grid"); this.row = row; this.column = column; } public int row() { return row; } public int column() { return column; } public GridCell nextColumn() { return new GridCell(row, column + 1); } @Override public boolean equals(Object other) { if (!(other instanceof GridCell cell)) return false; return row == cell.row && column == cell.column; } @Override public int hashCode() { return 1000 * row + column; }}public class Main { public static void main(String[] args) { GridCell first = new GridCell(2, 4); GridCell next = first.nextColumn(); System.out.println(first.column()); System.out.println(next.column()); }}Expected output:
45The original cell remains unchanged; a new cell holds the next coordinate.
Stable values, copies and equality
GridCell stores a row and column in the range 0–999. Its class is final, which prevents subclasses from adding behavior that undermines its intended design. Its private final primitive fields are set at construction; no method modifies them. nextColumn() returns a new cell instead of modifying the original. At column 999 it rejects the move through constructor validation. That policy is explicit, rather than silently wrapping around the grid.
== compares object identity. To compare GridCell values, override equals(Object) and hashCode() together. The annotation @Override asks the compiler to check that a method overrides an inherited method. Object is the base class of ordinary Java classes. The instanceof GridCell cell pattern checks the type and introduces a typed variable on success (null does not match); full polymorphism and pattern details come later. Equality uses both coordinates. Equal cells produce equal hash codes; unequal objects may generally have the same hash code. This deliberately bounded formula stays within int range. These contracts matter for hash-based collections, taught later.
A final reference does not freeze its target. DailyCounts copies its input int array before validating and copies again when returning it. The caller therefore cannot mutate the stored array through either the input or the accessor. A clone of a primitive array is sufficient here; copying an array of mutable objects does not automatically copy those objects. Immutability is a design property, not a keyword. Value objects commonly have value equality, but an immutable snapshot is not automatically a value object: DailyCounts intentionally does not define value equality in this example.
final class GridCell { private final int row; private final int column; GridCell(int row, int column) { if (row < 0 || row > 999 || column < 0 || column > 999) throw new IllegalArgumentException("cell outside grid"); this.row = row; this.column = column; } public int row() { return row; } public int column() { return column; } public GridCell nextColumn() { return new GridCell(row, column + 1); } @Override public boolean equals(Object other) { if (!(other instanceof GridCell cell)) return false; return row == cell.row && column == cell.column; } @Override public int hashCode() { return 1000 * row + column; }}public class Main { public static void main(String[] args) { GridCell a = new GridCell(3, 5); GridCell b = new GridCell(3, 5); System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(a.hashCode() == b.hashCode()); System.out.println(a.equals(null)); }}Expected output:
falsetruetruefalseSeparate objects may represent the same value; equality with null is false.
Check a boundary or variation
final class DailyCounts { private final int[] counts; DailyCounts(int[] counts) { if (counts == null) throw new IllegalArgumentException("missing counts"); this.counts = counts.clone(); for (int count : this.counts) { if (count < 0) throw new IllegalArgumentException("negative count"); } } public int[] counts() { return counts.clone(); } public int size() { return counts.length; }}public class Main { public static void main(String[] args) { int[] input = {4, 8}; DailyCounts day = new DailyCounts(input); input[0] = 90; int[] exposed = day.counts(); exposed[1] = 99; System.out.println(day.counts()[0]); System.out.println(day.counts()[1]); }}Expected output:
48Both attempted changes affect caller-owned arrays only.
Common mistakes
A private final int[] field alone is not immutable. Returning it directly or keeping the caller’s original array exposes a mutable alias. Similarly, a final class alone can still have mutable fields. Copy at the boundary when the representation is mutable, and define equality deliberately.
Practice
Implement DailyCounts with a private final int[] array. Reject null and negative counts, preserve empty arrays, and return a defensive copy. Verify that changing the original array or the returned array cannot change the snapshot.
Clone the input before validating its elements. Clone the stored array again in the accessor.
Next: Inheritance and super.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Immutable value objects — knowledge check
Apply the stated Java 21-compatible contracts and predict observable behavior.
What does nextColumn() do to the original cell?
Two distinct GridCell objects have matching coordinates. What is true?
If a.equals(b) is true, what must hold?
Why copy an incoming int array?
Why copy the array in counts()?