Lets Code JavaLets Code Java

Record type in Java



Records were introduced in Java 14. It is mainly used for creating data transfer objects.


Why do we need records?


Many times we require an immutable class for holding data. This object is called data transfer object. Before Java 14, creating a data transfer object involved a lot of boilerplate code. This code included getters, constructors and overriding toString methods.

Consider below code example:

class Person { private final int age; private final String name; public Person(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } @Override public String toString() { return "Person{" + "age=" + age + ", name=" + name + '}'; } } public class Main { public static void main(String[] args) { Person p1 = new Person(16,"Daniel"); System.out.println(p1); } }

Output:

Person[age=16, name=Daniel]

The declaration of all the final variables and constructors has required almost 25 lines of code. This has got developers thinking of something simpler to declare a data transfer class. That is when records were introduced.


How is record implemented?


Lets simplify the code to use record instead of class.

record Person(int age, String name){ } public class Main { public static void main(String[] args) { Person p1 = new Person(16,"Daniel"); System.out.println(p1); } }

Our 25 lines of code is reduced to a single line. Wasn't that amazing!

By default, records have the following characteristics:
  • Records are final and cannot be subclassed.
  • All variables in record are treated as private and final
  • Records have a toString, hashCode, and equals method generated automatically based on their component fields.
  • Records have a constructor with parameters for each component, in the order they were declared.
Records are recommended to be used when we don't wish to modify the data members and use them purely as a data object. Records are a useful addition to Java for defining simple data classes, and can help to reduce boilerplate code and improve code readability. However, they are still an experimental feature and may change in future versions of Java.

Terms of Use

Privacy Policy

Copyright © 2023 LetsCodeJava All Rights Reserved.