How to use Record in Java? Example

A Java record is a special kind of java class that is used as a 'data carrier' class without the traditional 'Java ceremony' (boilerplate). This represents an immutable state that is passing immutable data between objects. The Java Record was introduced with Java 14, and it is a preview feature because it must be enabled before it can be used. Records received via a database query, records returned from a remote service call, records read from a CSV file, and other use cases can all benefit from Java Record instances.

Java Record

The used java record syntax is simple and the record keyword is what tells the java compiler that this type of definition is a record.

public record Student(int studnetId, String studentName, int age) {}

Records are immutable data classes that just require field names and types. The java compiler generates the equals, hashCode, and toString methods, as well as the private, final fields, and public constructor methods, based on the previous code.



Other things to remember,

1. The class is marked final, which means we cannot create a subclass of it.

2. The class extends java.lang.Record, which is the base class for all records, much like java.lang.Enum is the base class for all enums.

3. There are two private final fields named after the three components of the record: studentId, studentName, and age.

By looking at its body, it’s easy to see that it just assigns the two arguments to the two fields. The constructor is equivalent to:
public Student(int studentId, String studentName, int age) {
  this.studentId = studentId;
  this.studentName = studentName;
  this.age = age;
}
There are three getter methods named studentId(), studentName() and age()

Three other methods are generated: toString(), hashCode() and equals(). They all rely on invokedynamic to dynamically invoke the appropriate method containing the implicit implementation.




Can use java record from using other java classes?
Here is an example of the java Record type Student defined in the above code example.

public class StudentExample {

  public static void main(String[] args) {
   Student student = new Student(18291,”James”,15);
   System.out.println( student.calculateMarks() );
   System.out.println( student.showClasses() );
  }
}

The java compiler will generate the calculateMarks() method and showClasses() methods and results will be displayed.

3. Key features of Java Record

Here are some important features of Record in Java which I think every Java programmer should know:

1. Java record type definition is final

2. You can have multiple constructors for Java Record.

3. Java Records also can have static methods.

4. Can add instance methods to a java record definition

5. We will discuss these key features with an example given below,

6. Java record type definition is final

7. Records are ostensibly definitive and only marginally unchangeable. Subclasses of a Java record type cannot be created.



Can you have multiple constructors for the Java Records?
Despite having its own default constructor, a Java record can have many constructors. Here's an example of a second constructor for the Student record type.

public record Student(int studentId, String studentName, int age) {
  public Student(int studentId, String studentName, int age) {
   this.studentId = studentId;
   this.studentName = studentName;
   this.age = age;
  }
}


Can you add static methods on Java records?
You can add static methods inside the java record definition. This allows having access to the methods without creating objects from the Java Record definition.

public record Student(int studentId, String studentName, int age) {
  public static String getStudentOverFifteen(Student student) {
   return student.age>15? student.studentName: "Not found";
 }
}


Can you add instance methods to a java record definition?
Similar to a regular Java class, you can also add instance methods to the Java Record definition. Here is the example of adding an instance method to the Student java record.

public record Student(int studentId, String studentName, int age) {
  public int getStudentNameInLowerCase() {
      return studentName.toLowerCase();
  }
}


So these are the key features of Java Record and here explain the benefits and restrictions of using the java record.



Here is an example of a Java record:


How to use Record in Java? Example





Benefits of having java records in your program.

1. equals(), hashCode(), toString(), constructor() and read accessors are generated for you

2. interfaces can be implemented

3. Restrictions or disadvantages of using Java Records.

4. a record cannot be extended, it’s a final class

5. a record cannot extend a class

6. The value (reference) of a field is final and cannot be changed


Records reduce the verbosity of many common classes by providing a direct way to model data as data, rather than simulating data with classes.

In a summary, records are immutable, which means they can't modify their state, and they eliminate a lot of boilerplate code. Records can be used to store data, as data carriers, or to return data from methods. So will meet you in the next tutorial.

Other Java tutorials and courses you may like:
  • How to parse JSON using Gson? (tutorial)
  • How to convert JSON to HashMap in Java? (guide)
  • 10 Things Java developers should learn?  (article)
  • How to ignore unknown properties while parsing JSON in Java? (tutorial)
  • Top 5 Websites to learn Java For FREE (websites)
  • How to parse JSON with date fields in Java? (example)
  • 10 Online courses to learn JavaScript in depth (courses)
  • How to parse a JSON array in Java? (tutorial)
  • Top 5 Courses to become full-stack Java developer (courses)
  • How to solve UnrecognizedPropertyException in Jackson? (solution)
  • 5 JSON parsing libraries Java Developers Should Know (libraries)
  • 10 Advanced Core Java Courses for Experienced Developers (courses)
  • 5 Courses to learn RESTful  API and Web services in Java? (courses)
  • 10 free courses to learn Java in-depth (resource)

Thanks for reading this article so far. If you like the Java Record example and tutorial, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.