Showing posts with label record in java. Show all posts
Showing posts with label record in java. Show all posts

Java Record


You have a Student data in the database . To return student data, you may write modal class as below. 
public class Student {
private int rollNumber;
private String name;
private String address;
public Student(int rollNumber, String name, String address) {
super();
this.rollNumber = rollNumber;
this.name = name;
this.address = address;
}
public int getRollNumber() {
return rollNumber;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
@Override
public int hashCode() {
return Objects.hash(address, name, rollNumber);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return Objects.equals(address, other.address) && Objects.equals(name, other.name)
&& rollNumber == other.rollNumber;
}

}

  • Here We have created Student modal with three fields . 
  • It has a constructor to create Student object.
  • It has getter methods to read student data. 
  • It also has overriden hashcode and equals methods to avoid duplicates.
  • If you have multiple tables, You need to all this boiler plate code for all the modal classes.
  • To avoid boiler plate code , We can use lombok library. 
  • We can rewrite the above Student modal class as below using lombok library.
 import lombok.Data;
@Data
public class Student {
private int rollNumber;
private String name;
private String address;
}

  • Instead of using lombok library, We can use Java record.
  • Record is special class which is used to store read only data. 
  • We can create a record using record keyword.  
Syntax
record recordName(variables declaration) {
//optional body
}
  

 

  • We can write the above Student modal class using record as below
public record Student(int rollNumber, String name, String address) {
}

  • We must declare variables within record parenthesis. These are private and final by default. 
  • Java compiler automatically creates constructor , getter methods, toString, equals , hashCode methods for these variables. 
  • Java will not generate setter methods. Because record is immutable. Once we have created record object, we can't modify it's data. 
  • We can use record keyword as variable name also. 
  • We can create record object using new keyword. 

public record Student(int rollNumber, String name, String address) {

}

public class Test {

public static void main(String[] args) {

List<Student> studentList = new ArrayList<>();

var student1 = new Student(1, "Hari", "Nellore");

var student2 = new Student(2, "krishna", "Chennai");

studentList.add(student1);

studentList.add(student2);

studentList.forEach(studentObj->{

System.out.println(studentObj.rollNumber()+" "+studentObj.name()+" "+studentObj.address());

});

} }

Output

1 Hari Nellore
2 krishna Chennai


  • Here getter methods are not prefixed by get word. They are same as variable name. 
  • To test equals, hashcode methods implementation , let's add Student objects to HashSet collection object. 

  • We can use generics with record. 
  • Static variables are allowed within record body. Instance variables are not allowed within record body. 
  • Both Static and instance methods are allowed to write inside record.
  • Abstract method is not allowed. 

 
 
How to write our own constructor in record:

  • Normally Java compiler generated constructor is sufficient. 
  • We may need to implement our own constructor to write validation conditions. For example if the name is empty or null throw an IllegalArgumentException exception.
  • We can implement constructor in two ways.
  1. Canonical constructor
  2. Non Canonical constructor

Canonical constructor

  • We can write canonical constructor in two forms . one is full form, other one is compact form.
  • Let's write canonical constructor in full form


  • Here constructor parameters should match exactly as the variables defined in record definition . Variables type , name and order must be same. 
  • You can write same constructor using compact  form as follows.
  • We don't need to declare constructor parameters. 
  • We don't need to initialize the record variables. 
  • At end of constructor , constructor parameters are automatically assigned to corresponding record variable. 
Non Canonical constructor

  • This constructor is useful when we want to add default values for some fields while creating record object.
  • We must call canonical constructor as first statement inside this constructor. 


  • Here we are using this keyword to call canonical constructor. Address field data is default Nellore for all record objects. 
I hope you have learned something new today. Thanks for reading . Please share it with your friends. Happy Coding 😀. Jai Hind !!




Different ways to run Spring boot App

 What are the different ways to run Spring boot app ?