Transient variables in Java
In this post we are going to examine what a transient variable is in Java and learn how to use them in the right context. In order to do that we are going to also take a quick look into the
Serializable interface and its usefulness.
1. Object Serialization and “transient” variables
Serialization is a process where a Java object can be written in a file as a sequence of bytes, containing all the object’s data as well as the meta-data (class name, method names, etc). Essentially we can serialize an object and then deserialize it anywhere else (e.g. another computer, another part of the program) and be able to use it as a standard object. Serialization by itself is a simple procedure and we are including an example of it in the code that follows.
Transient is a keyword that we can use for a class variable, which means that we don’t want this specific variable to hold on to any data at all after the process of serialization. This is extremely important, because there are scenarios in which we have a large amount of variables containing data, which do not need to be saved after serialization (maybe we need to just save a couple of things after processing and all the relevant data have no use anymore).
Next, we are going to show an example of how the “transient” keyword affects data after serialization.
2. Serialization with transient variables example
We have created a simple Student class which extends the
Serializable interface, containing two transient class variables. We are going to serialize and deserialize it in the same program, and the effect of the transient keyword will become very obvious.
Take notice, the class variables by themselves continue to exist, but they have no data associated with them, so when we try to print the student’s information by using the
toString() method, we don’t get an exception, just the values that are given to these variables by Java. So an empty
int is automatically assumed to have a value of zero, while a
String has a value of
null because it is an object.
3. Download the source code
This was an example of transient variables in Java.
You can download the full source code of this example here: Transient variables in Java
Last updated on May 22nd, 2020