Java Record Custom toString

1. Introduction

In this blog post, we will delve into customizing the toString method in Java Records. Java Records, introduced in Java 16, provide an efficient way to handle immutable data. By default, they come with an automatically generated toString method, but sometimes there's a need to customize this representation.

Definition

The toString method in Java is used to provide a string representation of an object. In Java Records, the toString method is automatically generated to include the record's state. However, developers can override this method to provide a custom string representation that suits their specific needs.

2. Program Steps

1. Define a Java Record.

2. Override the toString method in the record.

3. Create an instance of the record and print it to see the custom toString output.

3. Code Program

// Record with a custom toString method
public record Employee(String name, int age, String department) {

    // Overriding the toString method
    @Override
    public String toString() {
        return "Employee [Name: " + name + ", Age: " + age + ", Department: " + department + "]";
    }
}

public class Main {
    public static void main(String[] args) {
        Employee employee = new Employee("Alice", 30, "Development");

        // Using the overridden toString method
        System.out.println(employee);
    }
}

Output:

Employee [Name: Alice, Age: 30, Department: Development]

Explanation:

1. The Employee record is defined with fields name, age, and department.

2. The toString method is overridden in the Employee record to provide a custom string format.

3. In the main method, an instance of Employee is created.

4. When System.out.println is called with the Employee object, the custom toString method is invoked, displaying the employee's details in the specified format.

5. This example illustrates how the toString method in Java Records can be overridden to customize the representation of the record's data.


Comments