What does the transient keyword do in Java?
transient marks a field to be skipped during serialization. When the object is deserialized, that field gets its default value (null, 0 or false), which is useful for passwords, caches and values that can be recomputed.
Explain it simply
When you pack for a hostel, you leave behind things you do not want to carry, like the room key or a scratch notebook. transient tells Java "do not pack this field when saving the object".
Example
import java.io.*;
class User implements Serializable {
String name = "Asha";
transient String password = "secret123"; // skipped when saved
transient int loginCount = 7;
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(new User());
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
User u = (User) in.readObject();
System.out.println(u.name); // prints: Asha
System.out.println(u.password); // prints: null
System.out.println(u.loginCount); // prints: 0
}What to say in the interview
"transient applies only to instance fields and only matters for Java's built-in serialization. The field is not written, and after deserialization it holds the default value, not the original. I use it for sensitive data like passwords, for derived or cached values, and for fields that are not serializable such as a Thread or a database connection. Static fields are never serialized, so marking them transient has no effect."
Common mistakes
- Expecting a transient field to keep its initialiser value after deserialization.
- Marking a field transient and then being surprised that JSON libraries behave differently. They have their own rules.