Simple Java Record Example

In this post under Java, I will introduce you with example to Java’s Record classes.

Introduced in Java 16, is a immutable data class, whose main purpose is hold read only data.

Below shows how to create Record class.

Person Record

package core.record;

public record Person(int id, String name, int age) {
}

We save the file as “Person.java” similar to way we save a normal java class.

Points to note
1) We use the “record” keyword instead “class” keyword.
2) We declare all the fields with their types within a parenthesis next to record name itself as shown above.
3) We don’t need to add accessor methods. Java compiler internally adds accessor methods with same name as the fields. So in the above example, we will have accessor as “name()”
4) Java compiler internally add “toString” and “hashCode” methods.
5) Java compiler internally also adds a long constructor (constructor with all fields)
6) Each fields in the Record are implicitly final
7) The record itself is implicitly final
8) We can create a Record with no fields at all. It is legal

Next I will show the main class where we instantiate and use the Record class.

Main class

1 package core.record;
2
3 public class Example1 {
4 public static void main(String[] args) {
5 Person person = new Person(1, "john doe", 40);
6 System.out.println(person);
7 }
8 }

At line 5 we create an instance of “Person” record in same way we create an instance of normal java class.

At line 6 we print the instance to the console. At that time “Person” records “toString()” method is called, printing the string representation of the object to the console.

Below is the output

Output

    Person[id=1, name=john doe, age=40]

In this way we can create a Record in java

Leave a comment