What does the transient keyword mean?
📘 Syntax
transient int secretCode;
🎯 Why Use transient?
| Use Case | Why transient Helps |
|---|---|
| Sensitive data | Don’t serialize passwords, tokens, keys |
| Large or cache-only fields | Don’t waste space storing something you can rebuild |
| Non-serializable fields | Avoid exceptions for things like threads, sockets, or DB connections |
| Temporary runtime data | Timestamp, session ID, logs, etc. that don’t need to persist |
🔧 Example
import java.io.*;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
String username;
transient String password; // excluded!
public User(String username, String password) {
this.username = username;
this.password = password;
}
}
➕ Serialize:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user.ser"));
out.writeObject(new User("Stanley", "mySecret123"));
out.close();
➖ Deserialize:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("user.ser"));
User u = (User) in.readObject();
System.out.println(u.username); // "Stanley"
System.out.println(u.password); // null (not serialized) ✅
⚠️ What Value Does a transient Field Have After Deserialization?
| Type | Value |
|---|---|
String, Object | null |
int, long | 0 |
boolean | false |
You can re-initialize them in:
- A constructor
- A custom
readObject()method
🧵 TL;DR
| Feature | Meaning |
|---|---|
transient | Prevents a field from being serialized |
| Used for | Sensitive, temporary, or non-serializable data |
| Value after deserialization | Default Java value (null, 0, false) |
| Applies to | Fields only (not classes or methods) |