1. Overview

Java Records are a concise way to define immutable data containers in Java 14.

In this article, we’ll explore how custom constructors in Java Records give us greater control during object initialization by allowing for data validation and error handling.

2. Understanding Java Records

Records offer concise, readable syntax, enforce immutability, and generate standard implementations of commonly used methods like toString(), hashCode(), and equals(). These implementations are based on the record’s components and are generated automatically by the compiler.

A record is defined using the record keyword, followed by the name of the record and its components:

record StudentRecord(String name, int rollNo, int marks) {}

This record definition creates a new record class named StudentRecord with three components: name, rollNo, and marks.

The components are shallowly immutable instance variables, which means that they cannot be changed once a record instance has been created. However, mutable objects contained in a record can be changed.

By default, record components are private and can only be accessed through accessor methods. Custom methods and behavior can be added to a record, but the components must be kept private and accessed only through accessor methods:

@Test
public void givenStudentRecordData_whenCreated_thenStudentPropertiesMatch() {
     StudentRecord s1 = new StudentRecord("John", 1, 90);
     StudentRecord s2 = new StudentRecord("Jane", 2, 80);

     assertEquals("John", s1.name());
     assertEquals(1, s1.rollNo());
     assertEquals(90, s1.marks());
     assertEquals("Jane", s2.name());
     assertEquals(2, s2.rollNo());
     assertEquals(80, s2.marks());
}

In this example, we use the generated accessor methods to check the values of the records’ components.

3. How to Make a Custom Constructor for a Java Record

Custom constructors are crucial in Java records, as they provide the capability to add further logic and control the creation of record objects.

When compared with the standard implementation provided by the Java compiler, custom constructors offer more functionality to records.

To guarantee data integrity and be able to sort a StudentRecord by name, we can create a custom constructor for input validation and field initialization:

record Student(String name, int rollNo, int marks) {
    public Student {
        if (name == null) {
            throw new IllegalArgumentException("Name cannot be null");
        }
    }
}

Here, the custom constructor checks whether the name component is null or not. If it’s null, it throws an IllegalArgumentException. This enables us to validate the input data and ensure that the record objects are created in a valid state.

3.1. Sorting a List of StudentRecord Objects

Now that we’ve seen how to create a custom constructor for our record, let’s use this custom constructor in an example to sort a list of StudentRecord objects by name:

@Test
public void givenStudentRecordsList_whenSortingDataWithName_thenStudentsSorted(){
    List<StudentRecord> studentRecords = List.of(
        new StudentRecord("Dana", 1, 85),
        new StudentRecord("Jim", 2, 90),
        new StudentRecord("Jane", 3, 80)
        );

    List<StudentRecord> mutableStudentRecords = new ArrayList<>(studentRecords);
    mutableStudentRecords.sort(Comparator.comparing(StudentRecord::name));
    List<StudentRecord> sortedStudentRecords = 
      List.copyOf(mutableStudentRecords);

    assertEquals("Jane", sortedStudentRecords.get(1).name());
}

In this example, we created a list of StudentRecord objects that we were able to sort by name. We did not need to handle nulls while sorting since name will never be null.

To sum up, custom constructors in Java records provide the flexibility to add additional logic and control the creation of record objects. Although the standard implementation is straightforward, custom constructors make records more versatile and useful.

4. Benefits and Limitations of Custom Constructors in Java Records

As with any language feature, custom constructors in Java Records have their own set of benefits and limitations. Below, we’ll explore these in more detail.

4.1. Benefits

Custom constructors can bring several benefits to Java Records. They can be used to provide additional validation for the data being passed in, for instance, by checking if the values are within a certain range or if they meet certain criteria.

For example, let’s say we want to ensure that the marks field in the StudentRecord is always between 0 and 100. We can create a custom constructor that checks whether the marks field is within range. If it’s outside the range, we can throw an exception or set it to a default value like 0:

public StudentRecord {
    if (marks < 0 || marks > 100) {
        throw new IllegalArgumentException("Marks should be between 0 and 100.");
    }
}

Custom constructors in Java records can also be useful for extracting and aggregating relevant data into a smaller number of components, making it easier to work with the data in the record.

For example, let’s say we want to calculate the overall grade of a student based on his marks. We can add the grade field to the StudentRecord and create a custom constructor that calculates the grade based on the marks field. So, we can easily access the grade of a student without having to manually calculate it each time:

record StudentRecordV2(String name, int rollNo, int marks, char grade) {
    public StudentRecordV2(String name, int rollNo, int marks) {
        this(name, rollNo, marks, calculateGrade(marks));
    }

    private static char calculateGrade(int marks) {
        if (marks >= 90) {
            return 'A';
        } else if (marks >= 80) {
            return 'B';
        } else if (marks >= 70) {
            return 'C';
        } else if (marks >= 60) {
            return 'D';
        } else {
            return 'F';
        }
    }
}

In addition, custom constructors can set default values for their parameters if none are provided. This can be useful in cases where we want to provide default values for some fields or generate values automatically, such as generating a new ID or UUID:

record StudentRecordV3(String name, int rollNo, int marks, String id) {
    
    public StudentRecordV3(String name, int rollNo, int marks) {
        this(name, rollNo, marks, UUID.randomUUID().toString());
    }
}

4.2. Limitations

Despite the many benefits that custom constructors can bring to Java Records, they also come with certain limitations.

An overloading record constructor is required to explicitly delegate to another record constructor on the first line. The requirement exists because all construction must eventually delegate to the canonical constructor. Any overloading constructor must delegate to another constructor using this(...) on its first line, source: java-record-canonical-constructor.

For example, the below implementation will not work since we are not calling the record constructor on the first line:

record StudentRecordV3(String name, int rollNo, int marks, String id) {

    public StudentRecordV3(String name, int rollNo, int marks) {
        name = name.toUpperCase();
        this(name, rollNo, marks, UUID.randomUUID().toString());
    }
}

5. Conclusion

In this article, we’ve covered custom constructors in Java Records, along with their benefits and limitations.

To summarize, Java Records and custom constructors simplify code and enhance readability and maintainability. They have many benefits but their usage has some limitations that may not work for all use cases.

As always, the examples in this article can be found on GitHub.