Java 15

Java 15 – Record

Java 14 introduces a new class type record as preview feature to facilitate creation of immutable data objects. Java 15 enhances record type further. It is still a preview feature.

  1. Record object have implicit constructor with all the parameters as field variables.
  2. Record object have implicit field getter methods for each field variables.
  3. Record object have implicit field setter methods for each field variables.
  4. Record object have implicit sensible implementation of hashCode(), equals() and toString() methods.
  5. With Java 15, native methods cannot be declared in records.
  6. With Java 15, implicit fields of record are not final and modification using reflection will throw IllegalAccessException.

Example

Consider the following example −

Java15Tester.java

public class Java15Tester {
   public static void main(String[] args) {
      StudentRecord student = new StudentRecord (1, "Julie", "Red", "VI", 12);
      System.out.println(student.id());
      System.out.println(student.name());
      System.out.println(student);
   }
}
record StudentRecord(int id, 
   String name, 
   String section, 
   String className,
   int age){}

Compile and Run the program

$javac -Xlint:preview --enable-preview -source 15 Java15Tester.java
$java --enable-preview Java15Tester

Output

1
Julie
StudentRecord[id=1, name=Julie, section=Red, className=VI, age=12]

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs