Java Record Fields: Syntax and Behavior
Understand Java record fields: how they are declared, accessed, validated, and restricted, with practical examples and edge cases.

When you declare a Java record, the components in the record header define the data the record carries. The compiler turns each component into a private final field with the same name, and it also generates a canonical constructor, accessor methods, equals, hashCode, and toString. The generated fields hold the record's data; the record components are the declaration-level description that drives that generated code. This article explains how Java record fields are generated, accessed, validated, and restricted.
Understanding the distinction between components and fields matters when you work with the record body. Inside the body, this.x refers to the generated field for the component x, but you did not declare that field yourself. The compiler creates it for you.
How Record Fields Are Declared and Initialized
Record fields are always private final. The canonical constructor assigns each parameter to the corresponding field. You do not write this assignment yourself; the compiler does it. For example:
public record Rectangle(double width, double height) {}The generated constructor is equivalent to:
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}Because the backing fields are final, they must be assigned exactly once when the record is constructed. You cannot reassign them afterward. If you need to store a normalized version of a component, you can assign the normalized value to the constructor parameter in a compact constructor; the compiler then assigns that parameter to the backing field. No additional instance fields are available for derived state.
Accessor Methods and Field Visibility
The compiler generates accessor methods that match the component names. For Rectangle, you get width() and height(). These methods return the backing field values. The fields themselves are private, so the only way to read them from outside the record is through the accessors.
Rectangle r = new Rectangle(3.0, 4.0);
System.out.println(r.width()); // 3.0You can override an accessor in the record body if you need different behavior, such as returning a defensive copy or a computed value. The override does not change the backing field; it only changes what the method exposes. The compiler does not require an overridden accessor to return the original component value.
Custom Constructors and Field Validation
Records allow you to define a compact constructor to validate or normalize component values before they are assigned to the backing fields. The compact constructor syntax omits the parameters and assignments; you only write the validation or normalization logic. The compiler inserts the field assignments after your code.
public record Temperature(double celsius) {
public Temperature {
if (celsius < -273.15) {
throw new IllegalArgumentException("Temperature below absolute zero");
}
}
}Here, the validation runs before the field celsius is set. If the check fails, the object is never created, so the field is never assigned. This is the primary way to enforce invariants on record fields. You can also normalize the value by reassigning the parameter inside the compact constructor, but you cannot reassign the field directly.
If you need a different constructor signature, you can define an additional constructor that delegates to the canonical one. The delegation must call this(...) as the first statement. This allows you to provide defaults or convert types while keeping field initialization consistent.
Restrictions on Record Fields
Record components produce private final instance fields, and you cannot add any other instance fields in a record body. Static fields, static methods, and static initializers are allowed, but declaring an instance field in the record body is a compile error.
public record Person(String name) {
private static final int MAX_NAME_LENGTH = 100; // allowed
// private int age; // compile error
}This restriction is intentional. Records are designed to be transparent carriers of data. Allowing additional instance fields would break the contract that the state is exactly the component set. If you need extra state, you should use a class instead of a record.
Serialization and Reflection with Record Fields
Records can implement Serializable. When such a record is serialized, its serialized form is based on the record components, not the backing fields. During deserialization, the canonical constructor is invoked with the serialized component values. This means validation in a compact constructor runs again, which is generally desirable.
Reflection on record fields also behaves specially. The Class.getDeclaredFields() method returns the generated fields, but you can use getRecordComponents() to inspect the components in a more semantic way. The fields are private, but reflection can access them. However, because they are final, modifying them via reflection is unreliable and discouraged. The Record class provides no special methods to change field values; immutability is expected.
Performance and Memory Characteristics of Record Fields
Record fields are stored directly in the object, just like fields in a normal class. There is no additional indirection or wrapper. Because they are final, the JVM can sometimes optimize access more aggressively, but the practical performance difference compared to a hand-written immutable class is negligible. The main cost is the same: one field per component.
One subtle point is that records do not support lazy initialization of fields. If you need a cached derived value, you cannot add a non-static field to hold it. You could compute it in an accessor each time, but that repeats work. Alternatively, you can use a static map keyed by the record instance, but that introduces memory overhead and concurrency concerns. For most use cases, the simplicity of record fields outweighs the need for caching.
Working with Record Fields in Collections and Streams
Because record fields are exposed via accessor methods, you can use method references directly in streams. For example, sorting a list of Point records by their x component is straightforward:
List<Point> points = List.of(new Point(2, 5), new Point(1, 3));
points.stream()
.sorted(Comparator.comparing(Point::x))
.forEach(p -> System.out.println(p.x() + ", " + p.y()));The accessor methods are the only way to reach the fields, which keeps the API clean and consistent. This pattern works well with functional programming idioms and does not require any special handling.
Common Pitfalls with Record Fields
One common mistake is assuming that record fields are immutable if the component type is mutable. For example, record Bag(List<String> items) creates a final field items that references a List. The reference cannot be changed, but the list itself can be modified. This breaks the immutability expectation. If you need true immutability, you must defensively copy the component in the compact constructor or use an immutable collection type.
Another pitfall is overriding equals and hashCode incorrectly. Records generate these methods based on the fields, but if you override them, you must ensure they remain consistent with the field values. The generated implementations are correct for most cases, so overriding them is rarely necessary.
Finally, remember that record fields are not accessible from subclasses because records are final. You cannot extend a record. If you need inheritance, you must use a class. This is a deliberate design choice to keep records simple and unambiguous.
When to Choose a Record Instead of a Class
Use a record when your primary goal is to carry immutable data with minimal ceremony. If you need additional instance fields, mutable state, or inheritance, a class is the right choice. Records shine in data transfer objects, value objects, and message payloads. They also work well as keys in maps because of the value-based equals and hashCode.
The decision often comes down to whether the fields are the complete state. If the answer is yes, a record is appropriate. If you need to hide some fields or add derived state, a class gives you more control. In practice, record fields cover a large portion of the data-holder use cases, and the restrictions they impose often lead to cleaner designs.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.