Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Compact Constructor: Syntax and Use Cases

Learn how Java compact constructors work in records: syntax, validation, normalization, common mistakes, and practical examples.

~4 min readJava
#Java records#compact constructor#Java 16#validation
Illustration of a Java record with a compact constructor performing validation.

What Is a Compact Constructor in a Java Record?

When you declare a Java record (available in Java 16 and later), the compiler generates a canonical constructor that takes all record components as parameters and assigns them to the corresponding private final fields. Java's compact constructor provides a concise way to add validation or normalization to that constructor without writing the full parameter list. For many records, the default behavior is sufficient, but when you need to enforce invariants or transform input values, the compact constructor is the cleanest option.

A compact constructor has the same name as the record, no parameter list, and no explicit assignment statements. The assignments happen implicitly after the constructor body runs. This lets you add logic without repeating the field assignments.

Compact Constructor Syntax and Rules

A compact constructor is declared inside the record body, with the same name as the record, but without parentheses. Inside the body, you can refer to the record components directly. After the body completes, the compiler assigns the (possibly modified) component values to the fields. Here is a minimal example:

java
public record Person(String name, int age) { public Person { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } } }

In this compact constructor, age is the formal parameter, and you can modify it if needed. The implicit assignment happens after the body. You cannot assign to this.name or this.age; those assignments are generated. You also cannot declare local variables that shadow the component names.

If you write a compact constructor explicitly, you control its access modifier. The implicit canonical constructor generated when you omit an explicit constructor has the same access as the record. A public record usually declares a public compact constructor; a more restrictive constructor may be useful when you want to force clients to use a static factory instead.

Using Compact Constructors for Validation

Validation is the most common use case. Because the compact constructor runs before the fields are assigned, you can check the incoming values and throw exceptions early. This ensures that an invalid record instance cannot be created. For example:

java
public record Email(String address) { public Email { if (address == null || !address.contains("@")) { throw new IllegalArgumentException("Invalid email address"); } } }

The validation logic is centralized in the record definition, so every call to the constructor goes through the same checks. Other constructors and static factories must delegate to the canonical constructor, so they cannot bypass these checks. Standard Java serialization for records also invokes the canonical constructor when deserializing, so the compact constructor's validation applies there as well.

Normalizing Data in a Compact Constructor

You can also transform the input values before they are stored. For instance, you might want to trim whitespace or convert a string to lowercase. Inside the compact constructor, you can reassign to the component parameter:

java
public record User(String username) { public User { username = username.trim().toLowerCase(); } }

Here, username is the parameter, and reassigning it updates the value that will be assigned to the field. This is a concise way to normalize data without writing a static factory. Note that the reassignment happens before the implicit assignment, so you cannot read the field this.username inside the compact constructor; you only have the parameter.

Common Mistakes and Edge Cases

One common mistake is trying to assign to this.field inside the compact constructor. That is not allowed because the fields are final and the assignment is generated after the body. Another mistake is declaring a local variable with the same name as a component, which causes a compile-time error.

Records do not have a built-in copy method. If you add a copy method, have it call the record constructor so the compact constructor's checks run for the copy. For example:

java
public record Point(int x, int y) { public Point { if (x < 0 || y < 0) { throw new IllegalArgumentException("Coordinates must be non-negative"); } } public Point copy() { return new Point(x, y); } }

Declaring a compact constructor does not change the generated implementations of equals, hashCode, or toString; those methods use the final component fields after normalization.

Compact Constructors and Maintainability

Keeping validation and normalization inside the compact constructor makes the record self-contained. Other developers can see the invariants directly in the record definition, which improves maintainability. However, if the validation logic becomes complex, it might be better to extract it into a separate method or a utility class to keep the constructor readable. The compact constructor should be short and focused; if it grows too large, consider using a static factory with explicit validation.

When to Avoid Compact Constructors

Compact constructors are a good default, but not the only option. If validation or normalization logic becomes complex enough to obscure the record's purpose, a static factory with explicit validation may be clearer. A full canonical constructor with an explicit parameter list can also make the assignment step visible, at the cost of repeating the record component names. For most records, the compact constructor is the cleanest way to enforce invariants.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.