«Back to Home

Core Java

Topics

Transient Keyword In Java

Transient Keyword
 
Transient keyword is used in serialization. If we define any data member or a variable as a transient, it will not be serialized in Java.
 
In other words, we can simply say, if we don't want to serialize any data member of a class, we can mark it as a transient.
 
Let’s see an example, given below, with transient variable.
 
Code
  1. import java.io.Serializable;  
  2. public class Employee implements Serializable {  
  3.     int empid;  
  4.     String empname;  
  5.     transient int empage; //it will not be serialized  
  6.     int empsalary;  
  7.     public Employee(int empid, String empname, int empage, int empsalary) {  
  8.         this.empid = empid;  
  9.         this.empname = empname;  
  10.         this.empage = empage;  
  11.         this.empsalary = empsalary;  
  12.     }  
  13. }  
47

Now, serialize the object, which is given below.

Code
  1. import java.io.*;  
  2. public class EmployeeTest {  
  3.     public static void main(String args[]) throws Exception {  
  4.         Employee e1 = new Employee(101"Harry"2525000);  
  5.         Employee e2 = new Employee(136"Mia"2330000);  
  6.         FileOutputStream fos = new FileOutputStream("Data.txt");  
  7.         ObjectOutputStream os = new ObjectOutputStream(fos);  
  8.         os.writeObject(e1);  
  9.         os.writeObject(e2);  
  10.         os.flush();  
  11.         os.close();  
  12.         fos.close();  
  13.         System.out.println("Run successfully....");  
  14.     }  
  15. }  
48
 
Output

49

Now, deserialize the object, which is given below.

Code
  1. import java.io.*;  
  2. public class EmployeeTest1 {  
  3.     public static void main(String args[]) throws Exception {  
  4.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Data.txt"));  
  5.         Employee e1 = (Employee) ois.readObject();  
  6.         Employee e2 = (Employee) ois.readObject();  
  7.         System.out.println(e1.empid + " " + e1.empname + " " + e1.empage + " " + e1.empsalary);  
  8.         System.out.println(e2.empid + " " + e2.empname + " " + e2.empage + " " + e2.empsalary);  
  9.         ois.close();  
  10.     }  
  11. }  
50

Output

51

In the example, shown above, first we create the two classes Employee and EmployeeTest. The employee age variable of the Employee class is declared as transient due to which its value will not be serialized and if we deserialize the object, we will get the default value for transient variable. As we can see, that printing employee age of the Employee returns 0 because the value of employee age was not serialized.
 
Summary

Thus, we learnt, transient keyword is used in serialization. If we define any data member as transient, it will not be serialized and also learnt, how to use it in Java.