Wednesday, August 22, 2012
What is transient variable in Java - Serialization Example
What is transient variable in Java
transient variable in Java is a variable whose value is not serialized during Serialization and which is initialized by its default value during de-serialization, for example for object transient variable it would be null. this behavior can be customized by using Custom Serialized form or by using Externalizable interface. transient variable is used to prevent any object from being serialized and you can make any variable transient by using transient keyword. By the way difference between transient and volatile variable in Java is a famous Java interview question but transient variable is completely different than volatile variable which we have discussed in our post What is volatile variable in Java. In next section we will see complete example of serialization where we will first serialize an instance of Book class which implements Serializable and than de-serialize to see What is the value of transient variable after deserialization.
Here is a complete code example of Serialization in Java which demonstrate How to use transient variable in Java program; transient variables are not serialized during Serialization process and initialize with default value during deserialization.
If you look at this example of Serializing Object in Java you will realize that value of transient variables are not serialized and persisted and during deserialization those value are initialized with there default value which is zero in case of int variable. Since constructor also didn't run during de-serialization it won't get the value provided during constructor. In Summary use transient variable carefully in Java.
Other post you may like :