🚫 Use the transient Keyword
When a field is marked as transient, Java skips it during serialization — it will not be written to the stream, and when deserialized, it will be set to its default value.
import java.io.*;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
String username;
transient String password; // ❌ Do not serialize this
public User(String username, String password) {
this.username = username;
this.password = password;
}
}
🔄 When deserialized:
User u = new User("Stanley", "mySecret123");
serializeToFile(u); // Save to file
User restored = deserializeFromFile(); // Load from file
System.out.println(restored.username); // "Stanley"
System.out.println(restored.password); // null ✅ because it was transient
🧠 Why Use transient?
| Field Type | Reason to Exclude |
|---|---|
| Passwords / API Keys | 🛡 Security |
| Cache / derived values | ♻ Can be rebuilt, don’t waste space |
| Database connections / threads | 🔌 Can’t be serialized |
| Large fields not needed after restart | 💾 Save space |
⚠️ What Happens to Transient Fields?
| Field Type | Deserialized Value |
|---|---|
String | null |
int, long, double, etc. | 0 |
boolean | false |
| Object | null |
You can rebuild or initialize them in:
readObject()method- A custom constructor or init method
🧵 TL;DR
| Feature | Usage |
|---|---|
| Exclude field from serialization | transient keyword |
| Default value after deserialization | Yes |
| Used for | Sensitive, non-serializable, or unnecessary data |