Why the transient variable is not serialized in Java?

JavaObject Oriented ProgrammingProgramming

The Serialization is a process to persists java objects in the form of a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object. The Serialization is the translation of Java object’s values/states to bytes to send it over the network or to save it. On the other hand, the Deserialization is the conversion of byte code to corresponding java objects.

The Transient variable is a variable whose value is not serialized during the serialization process. We will get a default value for this variable when we deserialize it.

Syntax

private transient <member-variable>;

Example

import java.io.*;
class EmpInfo implements Serializable {
   String name;
   private transient int age;
   String occupation;
   public EmpInfo(String name, int age, String occupation) {
      this.name = name;
      this.age = age;
      this.occupation = occupation;
   }
   public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.app*end("Name:"+"\n");
      sb.append(this.name+"\n");
      sb.append("Age:"+ "\n");
      sb.append(this.age + "\n");
      sb.append("Occupation:" + "\n");
      sb.append(this.occupation);
      return sb.toString();
   }
}
// main class
public class TransientVarTest {
   public static void main(String args[]) throws Exception {
      EmpInfo empInfo = new EmpInfo("Adithya", 30, "Java Developer");
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("empInfo"));
      oos.writeObject(empInfo);
      oos.close();
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("empInfo"));
      EmpInfo empInfo1 = (EmpInfo)ois.readObject();
      System.out.println(empInfo1);
   }
}

Output

Name:
Adithya
Age:
0
Occupation:
Java Developer
raja
Published on 05-Aug-2019 15:36:29
Advertisements