**Serialization** is a mechanism in Java that lets you save the current state of an object as a sequence of bytes. You can write these bytes to a file on disk or send them over a network. **Deserialization** is the reverse process, taking the byte stream and rebuilding the live Java object in memory.
If an object contains sensitive fields (like credit card numbers or passwords) that should not be saved or transmitted, Java provides the **transient** keyword to exclude those specific fields from serialization.
Imagine you built a beautiful 3D plastic toy dollhouse (a live object in memory) and want to mail it to a friend:
- Serialization: You fold the dollhouse flat, pack the pieces in an envelope, and mail it (the byte stream). Your friend receives the envelope and pops the pieces back up to recreate the exact 3D house (deserialization).
- Transient: The dollhouse has a secret drawer containing real gold coins. Before flattening and mailing the house, you write **"transient"** on the drawer. The post office machine sees this tag and automatically **discards the coins** (excludes them from the package) to keep it safe. When your friend rebuilds the house, the secret drawer is present but empty (reverts to its default state, e.g. 0 or null).
Java Implementation
In this code, we serialize a student record. The id field is marked as transient, so it gets skipped during serialization and prints its default integer value 0 upon deserialization:
package io.practise;
import java.io.*;
public class TransientExample {
public static void main(String args[]) throws Exception {
TStudent s1 = new TStudent(211, "ravi");
// Serialize the Object to a file
FileOutputStream fout = new FileOutputStream("transient.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
out.close();
System.out.println("Object successfully written to disk.");
// Deserialize the Object from the file
ObjectInputStream in = new ObjectInputStream(new FileInputStream("transient.txt"));
TStudent s = (TStudent) in.readObject();
// Output fields. "id" was transient, so it restores to default integer value (0)
System.out.println("Restored Student ID (Transient): " + s.id);
System.out.println("Restored Student Name (Normal): " + s.name);
in.close();
}
}
class TStudent implements Serializable {
// transient field will not be serialized
transient int id;
String name;
public TStudent(int id, String name) {
this.id = id;
this.name = name;
}
}
Conclusion
Use the `transient` keyword to secure sensitive data fields, exclude loggers, or optimize performance by skipping large, temporary cache fields during object persistence operations.