What are Transient variables in Java? Explain.

Java 8Object Oriented ProgrammingProgramming

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).

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

In the following java program, the class Student has two instance variables name and age where, age is declared transient. In another class named EampleSerialize 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.

Example

 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 String getName() {
      return this.name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public int getAge() {
      return this.age;
   }
}
public class ExampleSerialize{
   public static void main(String args[]) throws Exception{
      Student std1 = new Student("Krishna", 30);
      FileOutputStream fos = new FileOutputStream("e:\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std1);
      FileInputStream fis = new FileInputStream("e:\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student std2 = (Student) ois.readObject();
      System.out.println(std2.getName());
   }
}

Output

Krishna
raja
Updated on 30-Jul-2019 22:30:26

Advertisements