Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

How to use Record in Java? Example Tutorial

Hello! Welcome, all again in the journey of Java. We are here today to learn a very interesting topic in Java: Records!  If you are wondering what is Record and how to use Record in Java then you have come to the right place. In this article, I am going to cover everything about the Record I know and will try to explain in simple words so that you know what is Records, what benefits it offers, and how you can use them. But before we dive in and understand what it is, let’s first understand what would happen without them. So, we would get an idea of the need and significance of Records. By the way, this is another article covering new Java features, earlier, I have covered Sealed ClassesCompletableFuturePhaser, and how to use var in Java. If you haven't read them already, you can check them to learn these useful Java features 

Life before Record in Java?

We deal with immutable classes, data, and objects. And for that, we have to write some boilerplate code. This is more relevant when you are writing a class or object which holds specific data, like data from a file, the result of a database query, or any immutable data. 

For making the data immutable, we will have to make the fields private and give the getter methods for the same. Also, we need to implement the equals() and hashcode() methods. Now, most of the time, we declare the fields and generate the remaining boilerplate code using IDE features.

Let’s take an example to understand this. Suppose we have an immutable class called “CourseHero” with 3 fields in it:
  1. Article name
  2. Article ID
  3. Writer name



Record Example in Java

Here is a simple example of how to use Record in Java. The class would look like this:

import java.util.Objects;

public final class CourseHero {
private final int articleID;
private final String articleName;
private final String authorName;

CourseHero(int articleID, String articleName, String authorName) {
this.articleID = articleID;
this.articleName = articleName;
this.authorName = authorName;
}

public int articleID() {
return articleID;
}

public String articleName() {
return articleName;
}

public String authorName() {
return authorName;
}

@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (CourseHero) obj;
return this.articleID == that.articleID &&
Objects.equals(this.articleName, that.articleName) &&
Objects.equals(this.authorName, that.authorName);
}

@Override
public int hashCode() {
return Objects.hash(articleID, articleName, authorName);
}

@Override
public String toString() {
return "CourseHero[" +
"articleID=" + articleID + ", " +
"articleName=" + articleName + ", " +
"authorName=" + authorName + ']';
}
}

Now, all of this code is boilerplate code and can be generated through IDE features. But, there must be a way to avoid this all and there is! Since Java 14, the Java language itself provides a feature to reduce the boilerplate code and the feature is Record.



What is Record in Java?

Java record is a special kind of Java class, that has a very precise, concise and, clutter-free syntax for handling immutable data. The syntax of Java Record is very easy and concise as below:


How to use Record in Java? Example Tutorial


Now, you all must be thinking, this is just the class skeleton, we still need to write the fields and all the boilerplate code? So friends, those who are thinking this, pause for 2 minutes and think over this points below:

Intriguing questions:

  1. Is this a class? If yes, why is ‘class’ not written in the syntax?
  2. If a record is a special kind of Java class, where is all the boilerplate code actually in the backend?


Record syntax:


Now, time for the reveal! The above syntax is correct and we don’t write ‘class’ in syntax, instead, we write ‘record’. We pass the fields in the parameters just as we would do in a constructor. Java will automatically know that the passed parameters are the fields of the class. 


Also, the boilerplate methods are also handled by Java itself! Let’s serve this by using our previous example and check what happens with the methods. 


Below is the code:


public class CourseHeroImplExample {

public static void main(String[] args) {

CourseHero hero = new CourseHero(1, "Records article", "Course Hero");

System.out.println( hero.articleID() );
System.out.println( hero.articleName() );
System.out.println( hero.authorName() );

hero.toString();
hero.hashCode();
}
}

Now, as seen above, java automatically created getter methods of the same name as that of our fields. Also, the toString() and hashCode() method are also automatically implemented by Java for us! So, as we can see, we get a clean, clutter-free code and all the boilerplate code is handled by just one keyword - record.

  
  

How to declare Constructor in Record in Java?


You guys must be probably thinking, a Record is a lifesaver! But wait, there’s still more to it. Over and above all the features we discussed above, we can also keep constructors as per our need. We just need to call the default one and handle the case as shown below:


What is record in Java? Example


Similarly we can create static and instance method too in our record. This can be observed in the example below:

Instance methods in a record:

For instance methods, it is similar to a normal Java class,


How to declare instance method in Java Record

Static methods in a record:

And, for static methods as shown below:


How to declare static method in Java Record


So, I hope you all probably love records for sure! :p

But, before using them, be sure to keep these points in mind

Important points:

  1. Records in java are final, thus, you will not be able to create sub-class, or to say, sub-records of a record.
  2. Java records were introduced in java 14, be sure to upgrade the version if you didn’t. Also, in java 14, they were released as a trial, be sure to set the trial settings on!


So, guys, this was it for this article. 

Learn Java and this time, do record it! :D


Other Core Java Articles You may like




Thanks for reading this Java Record tutorial so far. If you like my explanation and understand what is Record and how can you use Records in Java to write more cleaner code then please share this article with your friends and colleagues. 



No comments :

Post a Comment