Java transient keyword with example

Transient variable is the variable whose value is not serialized during serialization. You will get default value for these variable when you deserialize it.
Lets say you have Country class and you don’t want to Serialize population attribute as it will change with time, so you can declare population attribute as transient and it won’t serialized any more.

Java Serialization Tutorial:

Transient keyword example:

Create a classed called Country.java as below:
Create serializationMain.java as below:
When you run above program, you will get below output:
Now Create a classed called DeserializeMain.java as below:
When you run above program, you will get below output:
As you can see in above example, we have declared population as trasient,so after deserialization, its value became 0 (Default value for long)

Was this post helpful?

Leave a Reply

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