Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Value-based classes and object identity

Compare instances of value-based classes such as LocalDate using equals, not reference identity. Treat equal values as interchangeable and never use them as synchronization locks.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

a.equals(b)

Value rather than identity

Value-based classes and identity describes the contract of value-based classes. For LocalDate, the date matters: instances equal according to equals should be treated as interchangeable. Compare them using a.equals(b), not a == b.

Value-based classes have only final instance fields; referenced objects may nevertheless be mutable. Their equals, hashCode, and toString methods depend on field values, not identity. Factories do not promise a fresh identity on each call; accessible constructors are absent or deprecated.

Do not distinguish equal instances through identity hashing or identity-sensitive serialization mechanisms. Do not use synchronized (a): exclusive ownership of its monitor is not guaranteed. Identity-related behavior may change in future releases; synchronization may fail.

The example uses immutable LocalDate. a and b represent the same date, so equals returns true. plusDays(1) produces the next date without changing a. The code deliberately does not test ==.

Examples

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate a = LocalDate.of(2024, 2, 29);
        LocalDate b = LocalDate.parse("2024-02-29");
        System.out.println(a.equals(b));
        System.out.println(a.plusDays(1));
        System.out.println(a);
    }
}

Result

true
2024-03-01
2024-02-29

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources