Java transient modifier

In Java we have interesting modifier called transient to handle somewhat specialized situations. When an instance variable is declared as transient then its value need not persist when an object is stored to the persistence storage.

Transient variables cannot be persisted during serialization. A transient variable is a variable that can not be serialized. the transient keyword can be used to indicate the Java Virtual Machine (JVM) that the variable is not part of the persistent state of the object.

This can be used in a scenario where only some of the fields in a class are required to be saved and others are actually derived from the existing.

Before you are going to understand transient modifier in Java, you need to know also about Serialization and Deserialization process in Java.

Serialization is the process of writing the state of an object to a byte stream. This is useful when we want to save the state of our program such as an instance or object to a persistent storage area, such as a file or database.

Deserialization is the process for restoring these objects at a later time.

For example, look at the below class:

public class Trans {
    int x; // will persist
    transient int y; // will not persist
}

In the above example if an instance or object of type Tran is written to the persistence storage then the contents of y will not be saved, but the contents of x will be saved.

Let’s take an example for a situation, where a class has hundreds of attributes and a few of them need not be persisted but they are required for other purpose, at that time this transient modifiers come into play.

Now I will give an example to understand what is Java transient modifier and how it works.

Step 1. Create a class which implements Serializable interface. You must implement Serializable interface when we want to serialize an object to persistence storage area.

import java.io.Serializable;

public class Trans implements Serializable {
    private static final long serialVersionUID = 1L;

    private int x;
    private transient int y;

    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
}

Step 2. Create a main class in which we will test for Java transient modifier.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TransTest {

    public static void main(String[] args) {
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            File file = new File("trans.txt");
            Trans trans = new Trans();
            trans.setX(10);
            trans.setY(20);
            // Serialization
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(
                    file));
            objectOutputStream.writeObject(trans);
            // Deserialization
            objectInputStream = new ObjectInputStream(new FileInputStream(file));
            Trans trans2 = (Trans) objectInputStream.readObject();
            System.out.println(trans2.getX());
            System.out.println(trans2.getY());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Step 3. Run the main class. You will get following output in the console.

10
0

Why you are not getting here 20 for y because we have declared y as transient variable.

So its value is not serialized or during serialization process the transient field is ignored.

But notice that we have got 0 for y because it has got the default value during Deserialization process, hence y‘s actual value was ignored during Serialization process.

Therefore,

  • If the transient field is a primitive type then its value is 0
  • If the transient field is an object type then its value is null

So it is concluded that transient variable cannot be used in hashCode() method for calculating the hash code.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *