Java transient modifier

In Java we have interesting modifier called transient to handle somewhat specialized situations. When an instance variable is declared as transient then its value need not persist when an object is stored to the persistence storage.

Before we understand transient, we need to know also about Serialization and Deserialization process in Java.

Serialization is the process of writing the state of an object to a byte stream. This is useful when we want to save the state of our program such as an instance or object to a persistent storage area, such as a file or database.

Deserialization is the process for restoring these objects at a later time.

For example, look at the below class

In the above example if an instance or object of type Tran is written to the persistence storage then the contents of y will not be saved, but the contents of x will be saved.

Let’s take an example for on a situation where a class has hundreds of attributes and a few of them need not be persisted but they are required for other purpose, at that time this transient modifiers come into play.

Now we will take an example to understand better on transient modifier how it works.

Step 1. Create a class which implements Serialization interface. We must implement Serialization interface when we want to serialize an object to persistence storage area.


Step 2. Create a main class in which we will test for transient modifier.

Step 3. Run the main class. You will get following output in the console.

Why we are not getting here 20 for y because we have declared y as transient variable. So its value is not serialized or during serialization process the transient field is ignored.

But notice that we have got 0 for y because it has got the default value during Deserialization process, hence y‘s actual value was ignored during Serialization process.

If the transient field is a primitive type then its value is 0
If the transient field is a object type then its value is null

So we can conclude also transient variable cannot be used in hashCode() method for calculating the hashcode.

Thanks for your reading. Please do not forget to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.