The <code>transient</code> Keyword in Java

transient marks a field to be skipped during serialisation. When an object is serialised via Java's built-in Serializable mechanism, transient fields are not written; on deserialisation they're set to the type's default.

Usage

public class Session implements Serializable {
    private final String userId;
    private transient String authToken;       // never serialised
    private transient int cachedHash;         // derived, not persisted
}

What happens after deserialisation

session.authToken;          // null after deserialisation
session.cachedHash;         // 0

If the field can't meaningfully be zero or null, override readObject() to recompute it.

When to use it

  • Derived data β€” caches, memoised values, computed hashes that can be rebuilt.
  • Non-serialisable references β€” Thread, Connection, Logger, loggers, UI components.
  • Secrets β€” passwords, API tokens, private keys (though encryption is better).

JSON serialisation β€” a different world

Jackson, Gson and JSON-B ignore transient by default β€” they use their own annotations:

import com.fasterxml.jackson.annotation.JsonIgnore;

public class User {
    private String email;
    @JsonIgnore
    private String passwordHash;        // not emitted in JSON
}

Java Serialization β€” mostly legacy

Serializable is brittle (binary format, versioning pain, security issues) and discouraged for new code. Prefer:

  • JSON (Jackson, Gson) for APIs and persistence.
  • Protocol Buffers / Avro for high-throughput wire formats.
  • JDBC / JPA for database persistence.

In that world, transient rarely comes up.

Common mistakes

  • Expecting transient to affect JSON output β€” it doesn't. Use framework-specific annotations.
  • Marking a required field transient β€” silent data loss after serialisation.
  • Forgetting to rebuild transient state β€” deserialised objects arrive with default values.

Related

Pillar: Java keywords. See also volatile.