Course contentsShow
← Java
Lesson 2131 of 2,87042. SerializationFree lesson

What transient Means

Understanding how transient prevents fields from being serialized to the output stream.

What transient Means

You'll learn: How the transient keyword prevents specific fields from being saved during serialization.

The Problem: Not Everything Should Be Saved

When Java serializes an object, it automatically writes all instance fields to the output stream by default. But sometimes you have fields that shouldn't or can't be saved—like passwords, cached calculations, database connections, or temporary counters.

That's where transient comes in.

What transient Does

The transient keyword is a field modifier that tells Java's serialization mechanism: "Skip this field—don't write it to the stream."

When you mark a field as transient:

  • During serialization: the field is ignored completely
  • During deserialization: the field gets its default value (null for objects, 0 for numbers, false for booleans)

Plain-English Example

Think of serialization like packing a suitcase for a trip. Most of your belongings go in the suitcase. But marking something transient is like putting a "DO NOT PACK" sticker on it—it stays home, and when you arrive at your destination, that item simply isn't there.

public class UserSession implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private String username;           // will be serialized
    private transient String password; // will NOT be serialized
    private transient int loginCount;  // will NOT be serialized
}

After deserializing a UserSession, the username is restored, but password will be null and loginCount will be 0.

When to Use transient

  • Sensitive data (passwords, tokens)
  • Derived/calculated values that can be recomputed
  • Non-serializable resources (streams, connections)
  • Temporary caching fields

Key Takeaway: The transient keyword excludes fields from serialization—they're skipped during writing and reset to defaults during reading.