Understanding Transient In Java

Transient is a keyword in java. To understand transient you should have some basic idea on serialization.

It is generally comes in the context of serialization,as it gives us some control over serialization process to exclude some of object properties from serialization

If an instance variable is declared as transient then it is excluded during the serialization process, so if you don’t want any instance variable to be serialized then mark it as transient.

Only instance variables can be declared as transient to exclude them from serialization, so static variables should not be declared transient

During de-serialization process, transient variables are initialized with default values, so it is always a good practice to declare transient variables with some default values.

Generally  property which value can be derived from values of other property, does not required to be saved, should be declared transient.

Example Use : 

  class Example implements Serialzable {
      String firstName;
      String lastName;
      transient String fullName = firstName + " " +lastName;
      // here fullName can be derived from firstName and lastName
 }


  •   interest value can be derived from principal, rate and time
  •   word count value can be derived from the content variable
  •   logger variable 


Rule Of Thumb : 
 Any instance variable which is initialized with default values Or can be derived from other instance variables, should not be serialized and if an instance variable should not be serialized then it should be declared transient.

Different Combinations :

method variables as transient gives compilation error
static variable as transient has no meaning as static variables also don’t get persisted during serialization
final variable as transient creates problem during re-initializing during de-serialization process

Resource :


1 comment: