How transient works with final in Java serialization?


In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).

Transient variables − The values of the transient variables are never considered (they are excluded from the serialization process). i.e. When we declare a variable transient, after de-serialization its value will always be null, false, or, zero (default value).

Therefore, While serializing an object of a class, if you want JVM to neglect a particular instance variable you need can declare it transient.

public transient int limit = 55; // will not persist
public int b; // will persist

Example

In the following java program, the class Student has two instance variables name and age where, age is declared transient. In another class named SerializeExample we are trying to serialize and desterilize the Student object and display its instance variables. Since the age is made invisible (transient) only the name value is displayed.

 Live Demo

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable {
   private String name;
   private transient int age;
   public Student(String name, int age) {
      this.name = name;
      this.age = age;
   }
   public void display() {
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}
public class SerializeExample {
   public static void main(String args[]) throws Exception {
      //Creating a Student object
      Student std = new Student("Sarmista", 27);
      //Serializing the object
      FileOutputStream fos = new FileOutputStream("e:\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std);
      oos.close();
      fos.close();
      System.out.println("Values before de-serialization: ");
      std.display();
      System.out.println("Object serialized.......");
      //De-serializing the object
      FileInputStream fis = new FileInputStream("e:\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student deSerializedStd = (Student) ois.readObject();
      System.out.println("Object de-serialized.......");
      ois.close();
      fis.close();
      System.out.println("Values after de-serialization");
      deSerializedStd.display();
   }
}

Output

Values before de-serialization:
Name: Sarmista
Age: 27
Object serialized.......
Object de-serialized.......
Values after de-serialization
Name: Sarmista
Age: 0

Updated on: 15-Oct-2019

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements