Friday, March 29, 2024

What is transient variable in Java? Serialization Example

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 Externalizable interface. 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.

What is transient variable in Java? Serialization Example

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 Java and 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 class TransientTest {

 
    public static void main(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 (Exception e) {
            e.printStackTrace();
        }

    }
 
 
}

/*
 * A class that implements a Serializable interface and has a transient variable.
 */

class Book implements Serializable{
    private int ISBN;
    private String title;
    private String author;
    private transient int edition = 1; //transient variable not serialized

    public Book(int ISBN, String title, String author, int edition) {
        this.ISBN = ISBN;
        this.title = title;
        this.author = author;
        this.edition = edition;
    }

    @Override
    public String toString() {
        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 :

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. 

6 comments:

Feel free to comment, ask questions if you have any doubt.