Java 16 – Records

We all, Java programmers, have complained whenever we were forced to create a class or use maps just to hold some data whilst other newer languages provided some out-of-the-box data structure for the same.

Our problem has been addressed by introducing “Records” as part of the JEP 395 in Java 16. This construct is introduced with the aim of creating Immutable Data holders.

Let us look at the simplest Record

public class RecordsDemo {
    public static void main(String[] args) {
        Person person = new Person("Mohamed", "Sanaulla");
        System.out.println(person);
    }

}

record Person(String firstName, String lastName){}

The output of running the above code

The above record Person is compiled as if it was defined like below:

record Person(String firstName, String lastName){
    private final String firstName;
    private final String lastName;
    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName
    }
    public String firstName(){ return this.firstName; }
    public String lastName(){ return this.lastName; }
    //toString, equals and hashCode implementations
}

You can see that we have private final properties with accessor methods having the same name as the property and a constructor to initialize the private final properties. We are also provided with the implementation of toString, equals and hashCode. The equals and hashCode implementations are based on the data the record holds as shown in the code below:

Person person = new Person("Mohamed", "Sanaulla");
Person person1 = new Person("Mohamed", "Sanaulla");
System.out.println("Same Person? " + person.equals(person1));
The output of the above program

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading