Let's get started with a Microservice Architecture with Spring Cloud:
Custom Constructor in Java Records
Last updated: March 10, 2023
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 = new ArrayList<>(List.of(
new StudentRecord("Dana", 1, 85),
new StudentRecord("Jim", 2, 90),
new StudentRecord("Jane", 3, 80)
));
studentRecords.sort(Comparator.comparing(StudentRecord::name));
assertEquals("Jane", studentRecords.get(1).name());
}
In this example, we created a list of StudentRecord objects that we could sort by name. Since name will never be null, we did not need to handle nulls while sorting.
To sum up, custom constructors in Java records allow us 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. Additional Validations
Custom constructors can bring several benefits to Java Records. They can 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.");
}
}
Next, let’s create a StudentRecord with invalid marks:
assertThrows(IllegalArgumentException.class, () -> new StudentRecord("Jane", 2, 150));
As the test shows, we got the expected IllegalArgumentException.
4.2. Performing Additional Calculations
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 calculate it each time manually:
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';
}
}
}
Next, let’s give it a quick test:
StudentRecordV2 studentV2 = new StudentRecordV2("Jane", 2, 85);
assertEquals('B', studentV2.grade());
As we can see, the studentV2.grade property is correctly calculated.
4.3. Default Values for Properties
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. Next, let’s see an example:
record StudentRecordV3(String id, String name, Set<String> hobbies, boolean active) {
public StudentRecordV3(String name) {
this(UUID.randomUUID().toString(), name, new HashSet<>(), true);
}
}
The StudentRecordV3 record defines a String (id), a Set (hobbies), and a Boolean (active) properties. As we can see, we created a custom constructor that only accepts name and provides default values for other properties.
This can be convenient when we need to create an instance using default values:
StudentRecordV3 studentV3 = new StudentRecordV3("Jane");
assertThat(studentV3.id()).isEmpty();
assertThat(studentV3.hobbies()).isEmpty();
assertTrue(studentV3.active());
Sometimes, we may need one single object for an immutable default instance. Then, we can consider using a static variable. An example can explain it quickly:
record UserPreference(Map<String, String> preferences, boolean superUser) {
public static final UserPreference DEFAULT = new UserPreference(
Map.of("language", "EN", "timezone", "UTC"), false
);
}
The UserPreference record has a Map and Boolean parameter. Also, we declared the DEFAULT static variable for a default UserPreference instance with an immutable Map and a boolean value:
UserPreference defaultOne = UserPreference.DEFAULT;
assertFalse(defaultOne.superUser());
assertEquals(Map.of("language", "EN", "timezone", "UTC"), defaultOne.preferences());
UserPreference defaultTwo = UserPreference.DEFAULT;
assertSame(defaultOne, defaultTwo);
As the test shows, when we get the default UserPreference instance by UserPreference.DEFAULT, it’s always the same object.
4.4. 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 delegate to another record constructor on the first line explicitly. 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 BadStudentRecord(String name, int rollNo, int marks, String id) {
public BadStudentRecord(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.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.















