0Pricing
Java Academy · Lesson

Compact Constructors and Validation

Add validation logic inside compact constructors to ensure data integrity.

Compact Constructors

A compact constructor in a record runs before components are assigned. It lets you validate or normalize data without repeating the component assignments.

Standard vs Compact Constructor

The standard canonical constructor explicitly assigns components. The compact constructor omits the parameter list and assignments — they happen automatically after the body runs.

// Standard canonical constructor
record Range(int min, int max) {
    Range(int min, int max) {
        if (min > max) throw new IllegalArgumentException("min > max");
        this.min = min;  // explicit assignment
        this.max = max;
    }
}

// Compact constructor (same behavior, less code)
record Range2(int min, int max) {
    Range2 {  // no parameter list, no assignments
        if (min > max) throw new IllegalArgumentException("min > max");
        // components are assigned automatically after this block
    }
}

All lessons in this course

  1. Introducing Records
  2. Compact Constructors and Validation
  3. Custom Methods on Records
  4. Records vs Classes vs Lombok
← Back to Java Academy