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 !!




Text Blocks in Java


If you want to write multi line string in java , you must \n escape sequence which inserts new line. 
For example
public class Test {

public static void main(String[] args) {
String addressWithOutTextBlock = "H.No. 1234\n" + "Hitec city\n" + "Madhapur\n" + "Hyderabad - 500081";
System.out.println("Address WithOut TextBlock");
System.out.println(addressWithOutTextBlock);

}
}
Output:
Address WithOut TextBlock
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081

  • Using text block feature , you don't have to use \n to create new line.
  • It was added in java 15 version. To use this feature, you must use jdk 15 or higher version.
  • You write a text block using three double quotes characters. 
  • You can write any number of lines text within pair of  three double quotes characters.

public class Test {

public static void main(String[] args) {
String addressWithTextBlock = """
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081
""";
System.out.println("Address With TextBlock");
System.out.println(addressWithTextBlock);
}

}
Output:
Address With TextBlock
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081

  • Import point note, you must start writing text in next line of starting three double quote characters. 
  • If you write in the same line of starting three double quote characters, you get compile time error.
  • The ending three double quote characters, adds a new line after our text. 
  • If you don't want new line, you can write ending three double quote characters at the end of our text like below.
String addressWithTextBlock = """
H.No. 1234
Hitec city
Madhapur
Hyderabad - 500081""";
  • You can also use double quotes within text block. You don't have to use \" escape sequence.
String addressWithTextBlock = """
H.No. 1234
"Hitec city"
Madhapur
Hyderabad - 500081""";
Output:
H.No. 1234
"Hitec city"
Madhapur
Hyderabad - 500081
  • You can use two new escape sequences in text blocks \s, \. 
  • \s adds space , \ indicates line continuation. 
String addressWithTextBlock = """
H.No.\s1234
Hitec city \
Madhapur
Hyderabad - 500081""";
Output:
H.No. 1234
Hitec city Madhapur
Hyderabad - 500081
  • If there are any white spaces before each line, they will be removed as per below rules. 
  • If every line has same number of white spaces , those all white spaces are removed from each line.
String addressWithTextBlock = """
 H.No.1234
 Hitec city 
 Madhapur
 Hyderabad - 500081
""";
Output:
H.No.1234
Hitec city
Madhapur
Hyderabad - 500081
  • If there are odd number of white spaces before each line , least of number of white spaces will be removed. 
String addressWithTextBlock = """
   H.No.1234
     Hitec city 
       Madhapur
  Hyderabad - 500081
""";
Output:
 H.No.1234
   Hitec city
     Madhapur
Hyderabad - 500081
  • The ending three double quotes also decides how many white spaces to be removed. 
  • If the ending three double quotes placed before text, white spaces till that """ characters will be removed.
  • If the ending three double quotes placed after text, white spaces till first character of text will be removed.
String addressWithTextBlock = """
 H.No.1234
 Hitec city 
 Madhapur
 Hyderabad - 500081
""";
Output:
H.No.1234
Hitec city
Madhapur
Hyderabad - 500081
String addressWithTextBlock = """
      H.No.1234
      Hitec city 
      Madhapur
      Hyderabad - 500081
  """;
Output:
    H.No.1234
    Hitec city
    Madhapur
    Hyderabad - 500081

I hope you have learned something new .  Thanks for reading. If you have questions, please leave a comment below. You can watch same content video in my youtube channel Full Stack Adda .  
Happy Coding 😀. Jai Hind.



Different ways to run Spring boot App

 What are the different ways to run Spring boot app ?