What is transient variable in Java? Serialization Example (original) (raw)
What is a transient variable in Java?
transient variable in Java is a variable whose value is not serialized during Serialization and which is initialized by its default value during deserialization, for example for object transient variable it would be null. This behavior can be customized by using a custom Serialized form or by using the Externalizableinterface. A transient variable is used to prevent any object from being serialized and you can make any variable transient by using the transient keyword. You cannot make a local variable transient through and it's only the member variables which can be transient.
As the name suggest their value is not saved as part of object's state so they are not really represent an object state even though they are member variables. They are mostly used for security purposes.
A good example of transient variables are sensitive data which you don't want save like the password or any security or auth token. By making them transient and not persisting them you reduce the risk.
By the way difference between transient and volatile variable in Java is a famous Java interview question but transient the variable is completely different than volatile variable which we have discussed in our post What is a volatile variable in Java.
In the next section, we will see a complete example of serialization where we will first serialize an instance of Book class which implements Serializable and then de-serialize to see what is the value of the transient variable after deserialization?
How to use a transient variable in Java - Serialization Example
Here is a complete code example of Serialization in Java which demonstrates How to use a transient variable in Java program; transient variables are not serialized during Serialization process and initialize with default the value during deserialization.
Transient Keyword Example in Java
And, here is our complete Java program to demonstrate how to use a transient variable in Java:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
*
* Java program to demonstrate What is transient variable in Javaand fact that the value of
* transient variable is not serialized and during serialization it initialized with
* default value of that data type. e.g. If a transient variable is Object than after
* deserialization its value would be null.
*
* @author Javin
*/
public classTransientTest {
public static voidmain(String args[]) {
Book narnia = new Book(1024,"Narnia", "unknown",2);
System.out.println("Before Serialization: " + narnia);
try {
FileOutputStream fos = new FileOutputStream("narnia.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(narnia);
System.out.println("Book is successfully Serialized ");
FileInputStream fis = new FileInputStream("narnia.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Book oldNarnia = (Book)ois.readObject();
System.out.println("Book successfully created from Serialized data");
System.out.println("Book after seriazliation : " + oldNarnia);
} catch (Exceptione) {
e.printStackTrace();
}
}
}
/*
* A class that implements a Serializable interface and has a transient variable.
*/
class Book implements Serializable{
private int ISBN;
private Stringtitle;
private Stringauthor;
private transient intedition = 1; //transient variable not serialized
public Book(intISBN, String title, String author, intedition) {
this.ISBN = ISBN;
this.title = title;
this.author = author;
this.edition = edition;
}
@Override
public StringtoString() {
return "Book{" + "ISBN="+ ISBN + ", title=" + title + ", author=" + author + ", edition=" + edition + '}';
}
}
Output:
Before Serialization: Book{ISBN=1024, title=Narnia, author=unknown, edition=2}
Book is successfully Serialized
Book successfully created from Serialized data
Book after seriazliation : Book{ISBN=1024, title=Narnia, author=unknown, edition=0}
If you look at this example of serializing Object in Java you will realize that value of transient variables is not serialized and persisted and during deserialization, those values are initialized with their default value which is zero in the case of the int variable. Since the constructor also didn't run during de-serialization it won't get the value provided during the constructor. In Summary, use transient variables carefully in Java.
In general, transient variable are used for security purposes. For example, if an object contains a password field, marking it as transient ensures that the password is not stored when the object is serialized, reducing the risk of exposure.
Other Java Articles you may like :
- Top 10 Serialization interview questions in Java
- Difference between HashMap and ConcurrentHashMap in Java
- 10 Object-oriented design principles Java programmer should know
- Difference between TreeSet and HashSet in Java
- Top 10 Java Generics interview question and answers
- Difference between TreeMap and TreeSet in Java
- Difference between HashMap and ArrayList in Java
Thanks for reading this article so far. If you like my explanation of transient variables in Java and examples of how transient variables are used while serializing and de-serializing an object then please share it with your friends and colleagues.