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.

1
2
3
4
5
6
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.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on