Transient Keyword - ayushmathur94/DirectQuesAns_Prep GitHub Wiki
Transient keyword is used in the serialization process to prevent any variable from being serialized, so if you have any field which is not making sense to serialize, you can simply declare that as transient and it won't be serialized.
Serialization is a mechanism of converting the state of an object into a byte stream.
The modifier transient in java can be applied to field members of a class to turn off serialization on these field members.
class Employee implements Serializable { private String firstName; private String lastName; private transient String confidentialInfo; //Setters and Getters }
Now let’s serialize an instance of Employee class.
try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("empInfo.ser")); Employee emp = new Employee(); emp.setFirstName("Lokesh"); emp.setLastName("Gupta"); emp.setConfidentialInfo("password"); //Serialize the object oos.writeObject(emp); oos.close(); } catch (Exception e) { System.out.println(e); }
Now let’s de-serialize back into java object, and verify if “confidentialInfo” was saved or not?
try { ObjectInputStream ooi = new ObjectInputStream(new FileInputStream("empInfo.ser")); //Read the object back Employee readEmpInfo = (Employee) ooi.readObject(); System.out.println(readEmpInfo.getFirstName()); System.out.println(readEmpInfo.getLastName()); System.out.println(readEmpInfo.getConfidentialInfo()); ooi.close(); } catch (Exception e) { System.out.println(e); } Program Output. Console Lokesh Gupta null
Clearly, “confidentialInfo” was not saved to persistent state while serialization and that’s exactly why we use “transient” keyword in java.
I have modified the Employee class as below:
private String firstName; private String lastName; //final field 1 public final transient String confidentialInfo = "password"; //final field 2 public final transient Logger logger = Logger.getLogger("demo");
Now when I again run the serialization (write/read) again, below is the output:
Program output. Console Lokesh Gupta password null
This is strange. We have marked the “confidentialInfo” to transient; and still the field was serialized. For similar declaration, logger was not serialized. Why?
Reason is that whenever any final field/reference is evaluated as “constant expression“ see here, it is serialized by JVM ignoring the presence of transient keyword.
In above example, value “password” is a constant expression and instance of logger “demo” is reference. So by rule, confidentialInfo was persisted where as logger was not.
What if I remove “transient” from both fields? Well, then fields implementing Serializable references will persist otherwise not. So, if you remove transient in above code, String (which implements Serializable) will be persisted; where as Logger (which does NOT implements Serializable) will not be persisted AND “java.io.NotSerializableException” will be thrown.
-
A transient keyword can only be applied to fields or member variables. Applying it to the method or local variable is a compilation error.
-
Another important point is that you can declare a variable static and transient at the same time and the java compiler doesn't complain but doing that doesn't make any sense because the transient is to instruct "do not save this field" and static variables are not saved anyway during serialization.
-
In a similar way you can apply transient and final keywords together to a variable compiler that will not complain but you will face another problem of reinitializing a final variable during deserialization.
-
A transient variable in java is not persisted or saved when an object gets serialized.
Any variable whose value can be calculated from other variables doesn't require to be saved.
For example, if you have a field called "interest" whose value can be derived from other fields like principal, rate, time, etc then there is no need to serialize it.
Another example is word count if you are saving an article then no need to save word count because it can be created when the article gets deserialized.