Transient keyword in Java

In this tutorial, we will learn about Transient keyword in Java.

In Serialization, all the attributes/variables of an object are persisted. But if we don’t want to save the value of a particular variable, then this is the case where Transient keyword is used in Java.
Transient keyword provides you some control over serialization process and gives you flexibility to exclude some of object properties from serialization process. The Transient keyword in java can be applied to member variables of a class to turn off serialization on these. Each variable marked as transient will not be serialized.

Example of Java Transient Keyword:

Let’s create object.

Here we have marked brand variable as transient. Now serialize MyCar object. Let’s create class.

Let’s run the class and check the output.


We have serialized MyCar object, but transient variable brand has been serialized or not. Let’s check this by deserializing MyCar object.
Let’s create class.

Let’s run this class and check the output.


If you observe the output, the brand variables value is null and name and price variables values have been retrieved to what we have saved. This clearly indicates that the brand variable is not persisted since it was marked as transient.

Related posts

Leave a Comment