Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java Interfaces

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Class References

Java Useful Resources

Java - Record



In Java 14, an exciting feature record was introduced as a preview feature. The record feature helps in creating immutable data objects. In the Java 15 version, record types were enhanced further. In Java 14 and 15, in order to use a record, a flag --enable-preview has to be passed. From Java 16 onwards, this flag is not required as the record is a standard part of JDK.

Purpose of a Java Record

The prime purpose of a record is to create a data object or a POJO which is used to carry data in application program flow. In a multi-tier program, Domain/Model objects store the data captured from the data source and then these model objects are passed further to the application/UI layer to process the data and vice versa where UI/Application stores data in data objects and then pass these objects to Data layer to populate data sources.

As these data objects contain a lot of fields, developers are required to write a lot of setter/getter methods, parameterized constructors, overridden equals methods, and hashcode methods. In such a scenario, the record comes to the rescue as it provides most of the boilerplate code and the developer can focus on required functionalities only.

Features of Java Record

Following are the features of the record which makes the record an exciting feature:

  • Record objects have an implicit constructor with all the parameters as field variables.
  • Record objects have implicit field-getter methods for each field variable.
  • Record objects have implicit field setter methods for each field variable.
  • Record objects have an implicit sensible implementation of hashCode(), equals(), and toString() methods.
  • With Java 15, native methods cannot be declared in records.
  • With Java 15, implicit fields of record are not final and modification using reflection will throw IllegalAccessException.

Example Without Using Java Record

Let's create a simple program without using record where we're creating a Student object and printing its details. The Student has three properties, id, name and className. In order to create a student, we've create a parameterized constructor, setter, getter methods, equals and hashcode methods. Thus our Student class is completed with nearly 60+ lines.

package com.tutorialspoint;

public class Tester {
   public static void main(String args[]) {
      // create student objects
      Student student1 = new Student(1, "Mahesh", "XII");
      Student student2 = new Student(2, "Sudhir", "XII");

      // print the students
      System.out.println(student1);
      System.out.println(student2);

      // check if students are same
      boolean result = student1.equals(student2);
      System.out.println(result);

      // check if students are same
      result = student1.equals(student1);
      System.out.println(result);

      // get the hashcode
      System.out.println(student1.hashCode());
      System.out.println(student2.hashCode());
   }
}

class Student{
   private int id;
   private String name;
   private String className;

   Student(int id, String name, String className){
      this.id = id;
      this.name = name;
      this.className = className;
   }

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }

   @Override
   public String toString() {
      return "Student[id: " + id + ", name: " + name 
         + ", class: " + className + "]";
   }

   @Override
   public boolean equals(Object obj) {
      if(obj == null || !(obj instanceof Student) ) {
         return false;
      }
      Student s = (Student)obj;

      return this.name.equals(s.name) 
         && this.id == s.id 
         && this.className.equals(s.className);
   }

   @Override
   public int hashCode() {
      int prime = 19;
      int result = 1;
      result = prime * result + ((name == null) ? 0 : name.hashCode());
      result = prime * result + ((className == null) ? 0 : className.hashCode());
      result = prime * result + id;
      return result;
   }  
}

Let us compile and run the above program, this will produce the following result −

Student[id: 1, name: Mahesh, class: XII]
Student[id: 2, name: Sudhir, class: XII]
false
true
371251946
288252156

Example Using Java Record

Let's recreate above program using record where we're creating a Student object as record and printing its details. The Student has three properties, id, name and className. Here you can see the difference, the complete Student class is replaced with one line of code as Student record.

package com.tutorialspoint;

public class Tester {
   public static void main(String args[]) {
      // create student objects
      Student student1 = new Student(1, "Mahesh", "XII");
      Student student2 = new Student(2, "Sudhir", "XII");

      // print the students
      System.out.println(student1);
      System.out.println(student2);

      // check if students are same
      boolean result = student1.equals(student2);
      System.out.println(result);

      // check if students are same
      result = student1.equals(student1);
      System.out.println(result);

      // get the hashcode
      System.out.println(student1.hashCode());
      System.out.println(student2.hashCode());
   }
}

record Student(int id, String name, String className) {}

Let us compile and run the above program, this will produce the following result −

Student[id: 1, name: Mahesh, class: XII]
Student[id: 2, name: Sudhir, class: XII]
false
true
371251946
288252156

We can add custom methods in records as well. But generally it is not required.

Java Record for Sealed Interfaces

As records are final by default and can extend interfaces. We can define sealed interfaces and let records implement them for better code management.

Example: Use of Java Record for Sealed Interfaces

Consider the following example −

package com.tutorialspoint;

public class Tester {
   public static void main(String[] args) {
      Person employee = new Employee(23, "Robert");
      System.out.println(employee.id());
	  System.out.println(employee.name());
   }
}
sealed interface Person permits Employee, Manager {
   int id();
   String name();
}
record Employee(int id, String name) implements Person {}
record Manager(int id, String name) implements Person {}

Let us compile and run the above program, this will produce the following result −

23
Robert

Overriding Methods of Java Records

We can override a record method implementation easily and provide our own implementation.

Example: Override Java Record Methods

Consider the following example −

package com.tutorialspoint;

public class Tester {
   public static void main(String args[]) {
      // create student objects
      Student student = new Student(1, "Mahesh", "XII");

      System.out.println(student);
   }
}

record Student(int id, String name, String className) {
   public String toString() {
      return "Id: " + id + ", Name: " + name + ", class: " + className ;
   }
}

Let us compile and run the above program, this will produce the following result −

Id: 1, Name: Mahesh, class: XII
Advertisements