What is the transient keyword used for?
Author: Deron Eriksson
Description: This Java tutorial describes the use of a transient variable.
Tutorial created using: Windows XP || JDK 1.6.0_10


If a field of an object is transient, when that object is persisted (saved), the value of the transient field will not be persisted.

The TransientDemo class demonstrates this. It contains an inner class, MyDemo, which has a String field named "x" and a transient String field named "y". In the main() method, TransientDemo instatiates a MyDemo object with x set to "normal" and y set to "transient". This object is saved to the file system as a file called "mydemo.ser". We then read this persisted object and get a reference to it called "result". When we display the values of x and y after we've retrieved the object, we can see that the value of x is there but the value of y is null, since it wasn't persisted.

TransientDemo.java

package cakes;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TransientDemo {

	public static void main(String[] args) {

		class MyDemo implements Serializable {
			private static final long serialVersionUID = 1L;
			String x;
			transient String y;

			MyDemo(String x, String y) {
				this.x = x;
				this.y = y;
			}

			public String toString() {
				return "x is " + x + ", y is " + y;
			}
		}

		try {
			MyDemo md = new MyDemo("normal", "transient");
			System.out.println("Before save: " + md);

			// write object to file
			FileOutputStream fos = new FileOutputStream("mydemo.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(md);
			oos.close();

			// read object from file
			FileInputStream fis = new FileInputStream("mydemo.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			MyDemo result = (MyDemo) ois.readObject();
			ois.close();

			System.out.println("After save: " + result);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

The console output from executing TransientDemo is shown here:

Console output from executing TransientDemo

Before save: x is normal, y is transient
After save: x is normal, y is null