‹ Back to blog

Java Record

Record - A powerful data visualization and analysis tool

If you’re a Java developer, you’ve probably heard of Java records - a new feature that was introduced in Java 14. Record classes help to model plain data aggregates with less ceremony than normal classes.

Consider the following class definition:

PersonClass

It has the following characteristics:

  • All of its members are declared final
  • Its only methods consist of a constructor, Personn(String firstName, String lastName) and two accessors, getFitstName() and getLastName()

You can represent this class with a record 🎉:

PersonRecord

If you want your record’s constructor to do more than initialize its private fields, you can define a custom constructor for the record; this is called a compact constructor.

For example, the following record, Person, has two fields, firstName and lastName. Its custom constructor calls Objects.requireNonNull(firstName), which specifies that if one of the fields is initialized with a null value, then a NullPointerException is thrown. (Custom record constructors still initialize their record’s private fields.)

PersonClass1

The benefits of records are :

  • Create simple data objects without writing a lot of boilerplate code.
  • Java records is that they are immutable by default. This means that once you create a record, you cannot modify its fields.
  • Java records is that they are more concise and easier to read than traditional Java classes.

Java records are an exciting new feature in Java that can simplify your code and make it easier to work with data structures. By taking advantage of this new feature, you can write cleaner, more concise code that is easier to understand and maintain.