Home » Transient variable in Java

Transient variable in Java

by Online Tutorials Library

Transient variable in Java

A transient variable is a special type of variable which we create by using the transient keyword. It is a special type of variable which have a non-serialized value at the time of serialization. A variable that is initialized by its default value during de-serialization is known as a transient variable.

A transient variable plays an important role in preventing an object from being serialized. We can make any variable transient by using the transient keyword.

Usually, the interviewer asks the difference between the volatile and the transient variable. So, the volatile and the transient variables are both different from each other. The transient keyword is mainly used at the time of serializing an object, while the volatile keyword is related to the visibility of variables that are modified by multiple threads at the time of concurrent programming.

Both the volatile and transient keywords are rarely used by the programmer and not so much popular as compared to public, static or final.

In order to exclude the instance variables from the serialization process, we use the transient keyword. In order to indicate compiler to read the value of the variable from the main memory, we use the volatile keyword.

We can use the volatile keyword with static but cannot use the transient keyword with static.

Let’s take an example of a transient variable and understand how it works in Java:

TransientVariableExample.java

Output:

Transient variable in Java


Next TopicWeb crawler Java

You may also like