Learnitweb

transient keyword in Java and example

Variables may be marked transient to indicate that they are not part of the persistent state of an object. transient is the modifier applicable only for variables. If you define any data member as transient, it will not be serialized. At the time of serialization JVM ignores the original value of transient variable and save default value to the file.

transient keyword plays an important role to meet security constraints. There are various real-life examples where we don’t want to save private data in file. Another use of transient keyword is not to serialize the variable whose value can be calculated/derived using other serialized objects or system such as age of a person, birth date, etc.

It is recommended to serialize only those fields which represent a state of instance. It is good practice to use transient keyword with private confidential fields of a class during serialization.

static variable is not part of object state hence they won’t participate in serialization.

final variables participate in serialization directly by their values.

We’ll demonstrate the use of transient variable with the help of previous example. Using transient keyword with age saves default value to the file.

import java.io.*;

class Student implements Serializable {
	int rollNo = 100;
	transient int age = 25;
}

class SerializationExample {
	public static void main(String args[]) throws Exception {
		Student d1 = new Student();
		
		System.out.println("Serialization started");
		FileOutputStream fos = new FileOutputStream("test.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(d1);
		System.out.println("Serialization ended");
		
		System.out.println("Deserialization started");
		FileInputStream fis = new FileInputStream("test.ser");
		ObjectInputStream ois = new ObjectInputStream(fis);
		Student d2 = (Student) ois.readObject();
		System.out.println("Deserialization ended");
		
		System.out.println("rollNo: " + d2.rollNo);
		System.out.println("age: " + d2.age);
	}
}

Output

Serialization started
Serialization ended
Deserialization started
Deserialization ended
rollNo: 100
age: 0