What is the transient keyword in Java?
The transient keyword in Java is a field modifier that instructs the serialization mechanism to skip a field when converting an object to a byte stream. When an object implementing Serializable is serialized, every non-transient field is written to the output. A transient field is omitted entirely, and upon deserialization it receives the default value for its type: null for objects, 0 for numbers, false for booleans.
The primary use cases for transient are security and practicality. Sensitive fields like passwords or cryptographic keys should not be persisted to disk or sent over a network in serialized form. Additionally, fields that cannot be serialized — such as a thread, a database connection, or a cached computed value — must be marked transient to prevent a NotSerializableException at runtime.
A classic example is a Logger field. Logger instances are typically singletons retrieved from a factory and are not meaningfully serializable. Marking it transient prevents errors and avoids bloating the serialized form.
After deserialization, transient fields are null (or zero/false). If your class needs to re-initialize them, override the readObject(ObjectInputStream) method to restore them post-deserialization. For example, a transient cached result can be lazily recomputed on first access.
transient has no effect outside Java's built-in serialization. Frameworks like JSON serializers (Jackson, Gson) do not honor it by default — they have their own annotations (@JsonIgnore, @Expose) for field exclusion.
In summary, transient is a targeted escape hatch within the serialization contract: use it to protect sensitive data, avoid serialization errors for inherently non-serializable state, and exclude derived or cached values that are cheaper to recompute than to persist.
Correctly states transient excludes a field from serialization and that it receives a default value on deserialization. May not mention security implications or re-initialization via readObject.
Covers exclusion from serialization, default values on deserialization, security use case, non-serializable field use case, and notes transient is ignored by JSON frameworks.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment