A value is immutable information whose meaning comes from its contents, not from the identity of the object carrying it. The number 4 remains four regardless of its representation or whether Java stores it in one object or another. Values do not change over time, so asking for their identity or current state is beside the point. section 2.2
Java value objects use classes to represent this meaning. Their object identities still exist as implementation details, but equality is determined by state. Two separately created objects with the same state therefore represent the same value, while relying on reference identity can produce surprising results. section 2.2
Equal state, different objects
Two Vector instances constructed with (1.0, 3.0) are not the same Java object, but they are equal values. Conversely, comparing Integer objects with == can yield false for two 128 values and true for two 127 values because object identity is not value equality. section 2.2
Preserve value semantics by making the representation communicate immutability:
- Use final for variables and fields when reassignment would create an identity that tracks different values over time. section 2.2.3
- Make every component value-like; a single mutable reference can turn an apparently immutable object back into an identity. section 2.2.4
- Treat collections and nested objects carefully, because unmodifiable containers do not protect mutable elements. section 2.2.4
Listing 2.3 An example Value Class
class Vector {
private double x; #A
private double y; #A
public Vector(double x, double y) {
this.x = x;
this.y = y;
}
public double x() { return this.x; } #B
public double y() { return this.y; } #B
public boolean equals(Object o) { #C
if (this == o) return true; #C
if (o == null || getClass() != o.getClass()) return false; #C
Vector vector = (Vector) o; #C
return Double.compare(x, vector.x) == 0 #C
&& Double.compare(y, vector.y) == 0; #C
} #C
public int hashcode() { #C
return Objects.hash(x, y); #C
} #C
#D
}A compact Vector class exposes immutable coordinates through accessors and defines equality and hashing from those coordinates. section 2.2
Values become data when they are given domain meaning: an integer can represent a temperature, age, or voltage, while a value can also describe an action or decision. This makes value modeling useful beyond ordinary records and facts. section 2.8 section 2.3.1







