What is transient keyword in Java?
The transient keyword in Java serves the purpose of indicating that a particular field should not undergo serialization. By default, when an object is serialized, all of its variables are converted into a persistent state. However, in certain exceptional scenarios, there might be a need to exclude specific variables from this serialization process. In such cases, you can declare those variables as transient. This instructs the JVM to ignore the original value of the transient variable and instead save the default value associated with its data type.
The primary objective of using the transient keyword is to prevent the persistence of certain variables during serialization. It is considered a good practice to utilize the transient keyword with private and confidential fields of a class when serialization is involved. A prime example where the use of the transient keyword is prominent is with a Thread field. Generally, there is no rationale for serializing a Thread object, as its state is highly specific to the flow of program execution.Example
Serializing and Deserialization of Object
Serialization in Java refers to the process of converting an object's state into a byte stream, which can be stored or transmitted. Deserialization, on the other hand, is the process of reconstructing an object from a serialized byte stream. This allows objects to be saved to disk, sent over networks, or stored in databases.Serializing an Object
When you try to deserialize, you wont get back the transient field "age" because its not serialized.
The transient keyword is used to indicate that a field should not be serialized when an object is converted into a byte stream, allowing the exclusion of specific variables from the serialization process.