transient keyword in java
The "transient"
keyword can be applied to member variables of a class to indicate that the member variable should not be serialized when the containing class instance is serialized.
So transient fields will not be persisted when the object is serialized.
- class InterestExample{
- int principle;
- int rateOfInterest;
- int time;
- transient int interestAmt;
- }
class InterestExample{ int principle; int rateOfInterest; int time; transient int interestAmt; }
When an object of Employee class is being serialized, the fields principle ,rateOfInterest and time will be persisted, but the field interestAmt will not be persisted.
The transient
keyword can be applied only for member variable, in other words it can’t be applied for class, method and local variables.
When to use transient ?
By default, all the variables of an object get converted into a persistent state.
In some cases, we may want to avoid persisting some variables because we don’t have the need to persist those variables.
So we can declare those variables as transient
. If the variable is declared as transient, then it will not be persisted.
That is the main purpose of the transient keyword.
Example:
Any variable whose value can be calculated from other variables doesn’t require to be saved. For example if we have a field called “interest” whose value can be derived from other fields such as principle, rate, time etc then there is no need to serialize it.