All topics
library
intermediate

The transient Keyword

Exclude fields from Java serialization and understand its interaction with default values.

The transient keyword marks a field to be excluded from Java's default serialization mechanism. When an object is serialized, transient fields are skipped. When deserialized, they receive their type's default value (null for objects, 0 for numbers, false for boolean).

transient = a 'do not photograph' sticker on an item in a museum. When someone takes a photo of the exhibit (serialization), that item is left out. When the photo is printed (deserialization), there's a blank space where it was.

Key Concepts

1
Common use cases: 1. Security: passwords, tokens, encryption keys should not be persisted 2. Derived fields: cached computations that can be recalculated 3. Non-serializable fields: references to objects that don't implement Serializable (database connections, threads, streams) 4. Temporary state: UI-specific data, in-progress calculations
2
transient vs static: static fields are never serialized regardless of transient. They belong to the class, not the instance. transient only affects instance fields.
3
Custom serialization: if you need to serialize a transient field in a special way (e.g., encrypt a password), implement writeObject/readObject and handle it manually.
4
With modern Java, consider using records (which override serialization behavior) or external serialization formats (JSON with @JsonIgnore) where transient may not apply.