eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)