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
- import java.io.Serializable;
- public class Employee implements Serializable {
- int empid;
- String empname;
- transient int empage; //it will not be serialized
- int empsalary;
- public Employee(int empid, String empname, int empage, int empsalary) {
- this.empid = empid;
- this.empname = empname;
- this.empage = empage;
- this.empsalary = empsalary;
- }
- }
Now, serialize the object, which is given below.
Code
Code
- import java.io.*;
- public class EmployeeTest {
- public static void main(String args[]) throws Exception {
- Employee e1 = new Employee(101, "Harry", 25, 25000);
- Employee e2 = new Employee(136, "Mia", 23, 30000);
- FileOutputStream fos = new FileOutputStream("Data.txt");
- ObjectOutputStream os = new ObjectOutputStream(fos);
- os.writeObject(e1);
- os.writeObject(e2);
- os.flush();
- os.close();
- fos.close();
- System.out.println("Run successfully....");
- }
- }
Output
Now, deserialize the object, which is given below.
Code
Code
- import java.io.*;
- public class EmployeeTest1 {
- public static void main(String args[]) throws Exception {
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Data.txt"));
- Employee e1 = (Employee) ois.readObject();
- Employee e2 = (Employee) ois.readObject();
- System.out.println(e1.empid + " " + e1.empname + " " + e1.empage + " " + e1.empsalary);
- System.out.println(e2.empid + " " + e2.empname + " " + e2.empage + " " + e2.empsalary);
- ois.close();
- }
- }
Output
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.