Record in Java with Example

Record
DefinitionPurposeFeaturesSyntaxExampleConclusion
What is Record in Java ?

Record in Java is a new kind of type declaration which has a concise syntax for defining immutable data-only classes.

Purpose:

Record was introduced in Java 14 aimed at reducing the boilerplate code and improving the readability of immutable classes.

Features:
  • Record is final, meaning you can not extend a Java Record type
  • All the fields specified in the record declaration are final
  • Record can implement interface(s)
  • Instance methods can be added to a Java Record definition
  • Static methods can be added to a Java Record definition
Ideal For:

Record is a restricted form of a class like an enum. It’s ideal for “plain data carrier” classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors (e.g. POJO, DTO, etc.).

Syntax:

In Java a Record can be created by simply using the 'record' keyword instead of the 'class' keyword.

Example:

Here’s an example of a record in Java:

In this example, we’ve defined a record called 'Person' that has two fields: 'name' of type 'String' and 'age' of type 'int'. The 'record' keyword is used to define a record, followed by the name of the record and the fields it contains, just like a regular class.

The 'record' keyword generates a constructor, accessor methods, and a 'toString' method automatically, so you don’t need to write them yourself. This makes records very convenient to use when you need to define a simple data class.

Using Record Class:

Here’s an example of how you could use the 'Person' record:

In this example, we’ve created a new 'Person' record with the name “Alice” and age 25. We can access the values of the fields using the accessor methods generated by the record: 'name()' and 'age()'.

Conclusion:

Record class can have many innovative use cases, apart from being just a data carrier. The introduction of the keyword record that implicitly uses java.lang.Record class added another layer of convenience to it.

Share This Post On: