Java transient Keyword
In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the type of data stored in that instance. Deserialization performs exactly opposite operation. It converts the byte sequence into original object data. During the serialization, when we do not want an object to be serialized we can use a transient keyword.
Why to use the transient keyword?
The transient keyword can be used with the data members of a class in order to avoid their serialization. For example, if a program accepts a user’s login details and password. But we don’t want to store the original password in the file. Here, we can use transient keyword and when JVM reads the transient keyword it ignores the original value of the object and instead stores the default value of the object.
Syntax:
Or
When to use the transient keyword?
- The transient modifier can be used where there are data members derived from the other data members within the same instance of the class.
- This transient keyword can be used with the data members which do not depict the state of the object.
- The data members of a non-serialized object or class can use a transient modifier.
Example of Java Transient Keyword
Let’s take an example, we have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but we don’t want to serialize one value, e.g. age then we can declare the age data member as transient.
In this example, we have created two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
Let’s create a class with transient variable.
PersistExample.java
Output:
success
Now write the code for deserialization.
DePersist.java
Output:
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.
In this article, we have discussed use of transient keyword in Java, where to use transient keyword and implementation of transient keyword in a Java program.