Java Record Constructor Example

1. Introduction

This blog post delves into the use of constructors in Java Records. Introduced in Java 16, records provide a succinct way to create immutable data classes. We will explore how constructors enhance the functionality of records by enabling validation and customization during object creation.

Definition

A Java Record is a special type of class in Java designed for holding data. Records automatically generate equals(), hashCode(), and toString() methods. A record can have a constructor, which allows for data validation or normalization at the time of object creation.

2. Program Steps

1. Define a record with a compact constructor for validation.

2. Create instances of the record, with and without valid data.

3. Observe the behavior of the constructor during object creation.

3. Code Program

// Record with a compact constructor for validation
public record User(String username, String email) {
    public User {
        if (username == null || username.isBlank()) {
            throw new IllegalArgumentException("Username cannot be blank");
        }
        if (email == null || !email.contains("@")) {
            throw new IllegalArgumentException("Invalid email address");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            User validUser = new User("Alice", "alice@example.com");
            System.out.println("Valid User: " + validUser);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }

        try {
            User invalidUser = new User("", "aliceexample.com");
            System.out.println("Invalid User: " + invalidUser);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Valid User: User[username=Alice, email=alice@example.com]
Username cannot be blank
Invalid email address

Explanation:

1. The User record is defined with a compact constructor to validate username and email.

2. In the main method, two User instances are created: one with valid data and one with invalid data.

3. The constructor of the User record throws IllegalArgumentException if the username is blank or the email is invalid.

4. The output shows successful creation of a valid user and error messages for invalid user data.

5. This demonstrates how constructors in records can enforce data integrity and business rules at the time of object creation.


Comments