Java Record Keyword

In this tutorial, we will learn about record keyword in java. Java programmers often need to create classes that act as containers for data, also known as model or POJO classes. These classes serve as a medium for transferring data between different parts of the application. Before the introduction of the “record” keyword in JDK 14, creating such classes required writing a lot of boilerplate code. It includes fields, constructors, getters, and setters. This was a tedious and error-prone task that could lead to bugs and reduced code quality.

Thankfully, the record keyword java solves this problem by allowing developers to declare special types of classes that serve as data carriers. Records are concise, immutable, and self-contained, which makes them perfect for modeling data in Java applications. With records, you can define a class with just a few lines of code. The compiler generates the necessary constructors, accessors, and other methods automatically.

In addition to reducing the amount of boilerplate code required, records also make the intent of the code clearer and easier to understand. Since records are immutable by default, they help prevent bugs that can occur when data is accidentally modified. Moreover, records are designed to work seamlessly with other Java features, such as pattern matching and sealed classes, which makes them even more powerful.

In summary, the introduction of the Java keyword record in Java 14 is a game-changer for Java developers. It simplifies the process of creating model or POJO classes, improves code quality, and makes it easier to reason about data flow in Java applications.

java record keyword

Syntax of Record keyword in Java

public record Employee(Long id, String firstName, String lastName, String email, int age){
}

Adding Fields and Methods

Although it is feasible to include a new field and method, experts advise against it. If you do decide add a new field to the record, it is essential to ensure that it is static. It is not added to the component list. Similarly, if you choose to include a method, it should be able to access the internal state of the record fields.

It is important to note that the added fields. These methods will not be utilized in the compiler’s implicitly generated byte code. As a result, they will not be a part of any method implementation, including equals(), hashCode(), or toString(). Therefore, it is imperative to explicitly use them as required, rather than relying on the compiler to use them automatically.

Example :

public class Person {

    private final String name;
    private final String address;

    public Person(String name, String address) {
        this.name = name;
        this.address = address;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, address);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (!(obj instanceof Person)) {
            return false;
        } else {
            Person other = (Person) obj;
            return Objects.equals(name, other.name)
              && Objects.equals(address, other.address);
        }
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", address=" + address + "]";
    }
}

Example of Record Keyword in Java :

public record Employee(Long id, String firstName, String lastName, String email, int age) {
  static boolean minor;
  public boolean isMinor() {
    return minor;
  }
  public String fullName() {
    return firstName + " " + lastName;
  }
  public Employee {
    if (age < 18) {
      minor = true;
    }
  }
}

Now we can access them through

Employee employee = new Employee(1l, "Manuj", "Arora", "DeveloperHelps", 25);

System.out.println(employee.isMinor());   
System.out.println(employee.fullName());  

Output :

false
Manuj Arora

Canonical Constructors

In Java, a record class is a new type of class that was introduced in Java 16. It is a concise way of defining classes that are primarily used for storing data. It comes with several built-in features, including the canonical constructor.

The canonical constructor is a special type of constructor that is automatically generated by the Java compiler for record classes. It takes in all the record components as parameters and initializes them accordingly. The signature of the canonical constructor is predefined and specific to the construct of the record class.

However, it is possible to declare our own implementation of the canonical constructor in two different ways. The first way is to explicitly declare the constructor using the predefined signature in Java. This allows us to customize the initialization of the record components. It perform any necessary checks before the object is created.

record Invoice(String id, float amount) {
    static String prefix = String.valueOf(Calendar.getInstance().get(Calendar.YEAR))
            +String.valueOf(Calendar.getInstance().get(Calendar.MONTH)+1);
  
    public Invoice(String id, float amount){
        this.id=prefix+id.trim();
        this.amount=amount;
    }
}

The second way to declare a canonical constructor is through a compact constructor. In this approach, we simply provide the record name as the constructor without any parameters. The parameters are implicitly declared and assigned the same as the record components. This means that the compact constructor has the same functionality as the canonical constructor. With a more concise and readable syntax. It also eliminates the need to explicitly declare each parameter and use the “this” keyword.

In summary, the canonical constructor is a predefined constructor for record classes in Java that initializes the record components. It is possible to declare our own implementation of the canonical constructor . Using the predefined signature or through a compact constructor. The compact constructor provides a more concise and readable syntax. It eliminates the need for explicit parameter declaration and the use of “this” keyword.

record Invoice(String id, float amount) {
    static String prefix = String.valueOf(Calendar.getInstance().get(Calendar.YEAR))
            +String.valueOf(Calendar.getInstance().get(Calendar.MONTH)+1);
    public Invoice{
        id=prefix+id.trim();
        amount=amount;
    }  
}

Conclusions :

Java’s Record class offers a plethora of innovative use cases beyond serving as a mere data carrier. This is due to the introduction of the “record” keyword. It implicitly utilizes the java.lang.Record class and adds an extra layer of convenience. While it is true that this class is specifically designed for use as a data carrier. Its benefits go far beyond simply reducing the verbosity of POJO class declarations in accordance with Java’s language specifications.

While developers can certainly stick to traditional methods, the true impact of the Record class can only be experienced through its practical application. As the saying goes, the proof of the pudding is in the eating. Once implemented, developers can take advantage of its capabilities, such as concise syntax. Automatic implementation of standard methods like equals(), hashCode(), and toString(), and support for immutable properties. Furthermore, it can be used for modeling data types and even serve as an alternative to enums or interfaces.

Overall, Java’s Record class offers a modern and streamlined approach to data modeling and management. Its unique benefits are best experienced through its use in real-world applications

Follow for More Info – https://instagram.com/developerhelps?igshid=MzRlODBiNWFlZA==

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!