Importance of SerialVersionUID keyword in Java?

JavaObject Oriented ProgrammingProgramming

SerialVersionUID

  • The SerialVersionUID must be declared as a private static final long variable in Java. This number is calculated by the compiler based on the state of the class and the class attributes. This is the number that will help the JVM to identify the state of an object when it reads the state of the object from a file.
  • The SerialVersionUID can be used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible w.r.t serialization. If the deserialization object is different than serialization, then it can throw an InvalidClassException.
  • If the serialVersionUID is not specified then the runtime will calculate a default serialVersionUID value for that class based on various aspects of the class.

Example

import java.io.*;
class Employee implements Serializable {
   private static final long serialVersionUID = 5462223600l;
   int empId;
   String name;
   String location;
   Employee(int empId, String name, String location) {
      this.empId = empId;
      this.name = name;
      this.location = location;
   }
   void empData() {
      System.out.println("Employee Id is: "+ empId);
      System.out.println("Employee Name is: "+ name);
      System.out.println("Employee Location is: "+ location);
   }
}
public class EmployeeTest {
   public static void main(String[] args)throws Exception{
      Employee emp = new Employee(115, "Raja", "Hyderabad");
      emp.empData();
      FileOutputStream fos = new FileOutputStream("E:\Employee.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(emp);
      System.out.println("Object Serialized");
   }
}

Output

Employee Id is: 115
Employee Name is: Raja
Employee Location is: Hyderabad
Object Serialized


raja
Updated on 02-Jul-2020 09:02:37

Advertisements