In Java, the transient keyword is used to exclude specific fields of an object from being serialized. It ensures that sensitive or unnecessary data is not saved when the object is converted into a byte stream.
- Prevents sensitive information (like passwords) from being serialized.
- Ensures certain fields are not persisted when an object is written to a file or sent over a network.
- The default Serialization process ignores fields declared as transient.
- Transient fields are initialized with default values during deserialization.
import java.io.Serializable;
import java.util.Date;
class Test implements Serializable {
private transient String password; // will not be serialized
transient int age; // will not be serialized
private String username, email; // will be serialized
Date dob; // will be serialized
}
Explanation:
- password and age are marked transient, so they are not serialized.
- username, email, and dob are serialized as usual.
transient and static
- Static variables belong to the class, not the object.
- They are not part of the serialized state.
- Using transient with static has no effect.
- No compilation error occurs.
transient and final
- Final variables are serialized using their constant value.
- Declaring a final variable as transient has no impact.
- No compilation error occurs.
Example: with transient, static, and final
import java.io.*;
class Test implements Serializable {
int i = 10, j = 20;
transient int k = 30; // transient instance variable
transient static int l = 40; // transient static variable
transient final int m = 50; // transient final variable
public static void main(String[] args) throws Exception {
Test input = new Test();
// Serialization
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(input);
// Deserialization
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Test output = (Test) ois.readObject();
// Output values
System.out.println("i = " + output.i);
System.out.println("j = " + output.j);
System.out.println("k = " + output.k);
System.out.println("l = " + output.l);
System.out.println("m = " + output.m);
}
}
Output
i = 10 j = 20 k = 0 l = 40 m = 50
Explanation:
- i and j are serialized normally.
- k is transient, so after deserialization it gets default value 0.
- l is transient static, so its value remains 40, unaffected by serialization.
- m is transient final, so it retains its constant value 50.