Transient Keyword In Java
Java Transient Keyword
Java transient keyword is used in serialization mechanism. If you define any data member(variable) as transient, it will not be serialized.
Let's take an example, I have declared a class as Employee, it has four data members id, name, age and salary. If you serialize the Employee Class object, all the values will be serialized but I don't want to serialize one value, e.g. salary then we can declare the salary data member as transient.
Example of Java Transient Keyword
In this example, we have created the two classes Employee and PersistTestExample. The salary data member of the Employee class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
Let's create a class with transient variable.
import java.io.Serializable; public class Employee implements Serializable{ int id; String name; int age; transient int salary;//Now it will not be serialized public Student(int id, String name,int age,int salary) { this.id = id; this.name = name; this.age=age; this.salary=salary } }
Now write the code to serialize the object.
import java.io.*; class PersistTestExample{ public static void main(String args[])throws Exception{ Employee emp =new Employee(211,"ravi",22,2000);//creating object writing object into file FileOutputStream fs=new FileOutputStream("test.txt"); ObjectOutputStream out=new ObjectOutputStream(fs); out.writeObject(emp); out.flush(); out.close(); fs.close(); System.out.println("success"); } }
Output:
success
Now write the code for deserialization.
import java.io.*; class DSerialPersistTest{ public static void main(String args[])throws Exception{ ObjectInputStream input=new ObjectInputStream(new FileInputStream("test.txt")); Employee emp=(Employee)input.readObject(); System.out.println(emp.id+" "+emp.name+" "+emp.age+" "+emp.salary); input.close(); } }
output :
211 ravi 22 0
As you can see, printing salary of the employee returns 0 because value of salary was not serialized.
post a comment