Java 28 Value Objects Explained with Examples (JEP 401)
Java 28 introduces value objects as a preview feature through JEP 401. This is the first part of Project Valhalla to arrive in the JDK, and it changes a fundamental assumption in Java: not every object needs an identity.
Value objects let you model simple immutable data without object identity. The JVM can then optimize memory layout and access patterns, especially when many value objects are stored in arrays or collections.
Table of Contents
- What Are Value Objects?
- Identity vs Value
- Value Class Syntax
- Value Records
- Equality and ==
- Performance Benefits
- When to Use Value Objects
- Limitations and Caveats
- FAQs
What Are Value Objects?
A value object is an instance of a value class, declared with the value modifier. Value objects have no identity. Two value objects with the same field values are considered the same value.
This differs from regular Java objects, which have identity. Two regular objects with identical field values are still different objects if they occupy different memory locations.
Core characteristics
- Declared with the
valuemodifier. - Fields are implicitly final.
- No synchronization on value objects.
- No identity-based operations such as
System.identityHashCode. - Equality is based on field values.
- The JVM may flatten value objects in arrays and fields.
Value objects are a preview feature in JDK 28. You must enable preview features to compile and run them.
Identity vs Value
Understanding identity is the key to understanding value objects.
Identity objects
A regular Java object has identity. Even if two objects contain the same data, they are different objects.
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a == b); // false
Each new call creates a distinct object with its own identity.
Value objects
A value object has no identity. Its value is defined entirely by its fields.
value class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() {
return x;
}
public int y() {
return y;
}
}
Two Point value objects with the same coordinates represent the same value.
Why identity matters
| Operation | Identity object | Value object |
|---|---|---|
| Object identity | Yes | No |
| Reference equality | Compares identity | Compares value |
| Synchronization | Supported | Not supported |
| Flattening in arrays | Not possible | Possible |
| Null representation | Reference can be null | Requires a default value representation |
Value Class Syntax
The only new syntax is the value modifier. Everything else looks like a normal Java class.
Basic value class
value class Money {
private final long cents;
public Money(long cents) {
this.cents = cents;
}
public long cents() {
return cents;
}
public Money plus(Money other) {
return new Money(this.cents + other.cents);
}
}
Compile with preview features
javac --release 28 --enable-preview Money.java
Run with preview features
java --enable-preview Money
Fields are implicitly final
Value class fields are implicitly final. You do not need to write final, and you cannot reassign fields after construction.
value class Temperature {
private double celsius;
public Temperature(double celsius) {
this.celsius = celsius;
}
}
Constructors must initialize all fields
Every field must be assigned before construction completes. This ensures that a value object always represents a valid value.
value class Range {
private final int start;
private final int end;
public Range(int start, int end) {
if (start > end) {
throw new IllegalArgumentException("start must be <= end");
}
this.start = start;
this.end = end;
}
}
Value Records
Records are natural candidates for value classes. A value record combines record syntax with value semantics.
Value record example
value record Point(int x, int y) {
}
This declares a record whose instances are value objects. The record components become fields, and the compiler generates the constructor, accessors, equals, hashCode, and toString methods.
Value record with validation
value record Email(String address) {
public Email {
if (address == null || !address.contains("@")) {
throw new IllegalArgumentException("Invalid email address");
}
}
}
Value record with behavior
value record Money(long cents) {
public Money plus(Money other) {
return new Money(this.cents + other.cents);
}
public Money minus(Money other) {
return new Money(this.cents - other.cents);
}
public boolean isGreaterThan(Money other) {
return this.cents > other.cents;
}
}
Records vs value records
| Feature | Record | Value record |
|---|---|---|
| Immutable data carrier | Yes | Yes |
| Object identity | Yes | No |
| Possible flattening | No | Yes |
| Reference equality behavior | Identity-based | Value-based |
| Synchronization | Supported | Not supported |
Equality and ==
One of the most important changes with value objects is how == behaves.
Identity objects
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true, if equals is implemented
Value objects
value record Point(int x, int y) {
}
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a == b); // true
For value objects, == compares values rather than references. This makes value objects behave more like primitive values.
Null handling
Value objects can still be null when stored in reference variables. However, the JVM may represent them more efficiently when they are non-null and stored in arrays or fields.
Point point = null;
if (point == null) {
System.out.println("No point");
}
Performance Benefits
The main performance benefit of value objects is flattening. When the JVM can flatten value objects, it can store their fields directly in arrays or containing objects instead of storing references to separate heap objects.
Without flattening
Point[] array
┌─────────┐
│ ref 1 │ ──> Point object (x, y)
│ ref 2 │ ──> Point object (x, y)
│ ref 3 │ ──> Point object (x, y)
└─────────┘
With flattening
Point[] array
┌─────────┬─────────┬─────────┐
│ x1, y1 │ x2, y2 │ x3, y3 │
└─────────┴─────────┴─────────┘
Flattened storage can reduce memory overhead, improve cache locality, and reduce pointer chasing.
Example: large array of points
value record Point(int x, int y) {
}
public class PointBenchmark {
public static void main(String[] args) {
Point[] points = new Point[1_000_000];
for (int i = 0; i < points.length; i++) {
points[i] = new Point(i, i * 2);
}
long sum = 0;
for (Point point : points) {
sum += point.x();
}
System.out.println(sum);
}
}
With value objects, the JVM may store the points in a compact flattened layout. The exact optimization depends on the JVM implementation and the context in which the value objects are used.
Potential benefits
- Lower memory usage for large arrays of small values.
- Better CPU cache utilization.
- Fewer object allocations.
- Less pointer chasing.
- Improved performance for numeric and data-heavy workloads.
When to Use Value Objects
Value objects are best suited for small, immutable data types that represent a value rather than an entity.
Good candidates
- Coordinates, points, and dimensions.
- Money and currency amounts.
- Dates, times, and durations.
- Ranges and intervals.
- Color values.
- Measurements and units.
- Small identifiers with validation.
Poor candidates
- Entities with lifecycle and identity, such as a database row.
- Objects that require synchronization.
- Large objects with many fields.
- Objects that rely on reference identity.
- Mutable state holders.
Example: domain value object
value record Quantity(int value) {
public Quantity {
if (value < 0) {
throw new IllegalArgumentException("Quantity cannot be negative");
}
}
public Quantity add(Quantity other) {
return new Quantity(this.value + other.value);
}
}
Limitations and Caveats
Value objects are a preview feature. The syntax and behavior may change in future Java releases.
Preview feature requirement
You must compile and run with preview features enabled. Production use should wait until the feature is finalized.
javac --release 28 --enable-preview MyClass.java
java --enable-preview MyClass
No synchronization
You cannot synchronize on a value object because it has no identity.
// Not allowed
synchronized (point) {
// ...
}
Identity-sensitive APIs
APIs that depend on object identity may not work as expected with value objects. Review code that uses identity hash codes, weak references, or identity-based maps.
Migration considerations
- Do not convert existing classes to value classes without reviewing identity usage.
- Check serialization behavior.
- Review frameworks that rely on object identity.
- Test with realistic workloads before adopting preview features.
- Wait for finalization before using value objects in production.
FAQs
What are value objects in Java 28?
Value objects are instances of value classes declared with the value modifier. They have no identity and are defined entirely by their field values.
Are value objects final in Java 28?
Value objects are a preview feature in JDK 28. You must enable preview features to use them.
What is the difference between a record and a value record?
A record has object identity. A value record has no identity and may be flattened by the JVM for better memory layout and performance.
Does == compare values for value objects?
Yes. For value objects, == compares values rather than references.
Can value objects be null?
Yes, when stored in reference variables. The JVM may use more efficient representations when value objects are non-null and stored in arrays or fields.
Are value objects part of Project Valhalla?
Yes. JEP 401 Value Objects is the first part of Project Valhalla to arrive in the JDK.
Should I use value objects in production now?
Not yet. They are a preview feature in JDK 28. Experiment in non-production code and wait for finalization before adopting them broadly.
What is flattening?
Flattening is a JVM optimization that stores value object fields directly in arrays or containing objects instead of storing references to separate heap objects.
Final Thoughts
Java 28 value objects are a significant step toward more efficient data modeling in Java. They let you express immutable values without identity overhead, and they open the door to memory and performance improvements that were previously unavailable to Java objects.
Start experimenting with value records in small, non-critical areas such as coordinates, money, and measurements. Avoid converting identity-sensitive classes, and wait for the feature to finalize before using it in production.
Next in this series: Structured Concurrency in Java 28: StructuredTaskScope and ScopedValue
Comments
Post a Comment