Transient variable in Java is used to show that a particular field should not be serialized when the class instance containing that transient variable being serialized.
It means if you don't want any information or field to be serialized, just add Transient keyword and it will not be considered or will be ignored by serialization mechanism.
Serialization mechanism works in the following way: State of the object is converted into stream of bytes and stored in a file, it can also be brought back to the actual state of bytes using deserialization.
Serialization is used in the networking programming where an object must be converted in bytes in order to be transmitted through network. The object's state is saved in JVM, which reads the bytecode and then recovers it during deserialization.
This state of conversion is called persistence. At this time, by default, all the variables get converted into a persistent state. To avoid some variables from getting converted, one must declare the variable Transient keyword.
On Deserialization, transient variable is initialized by its default value.
For example, if a variable is declared as Transient in a class that is being serialized and that class is written to an ObjectStream, the value of the variable becomes null when the class is retrieved from the ObjectStream.
This is used in times where an object becomes invalid once it is serialized or de-serialized.
Liked it! Share this Tutorial