Sobes.tech
Junior — Middle

Can you explain the purpose and use of the transient modifier in Java?

sobes.tech AI

Answer from AI

The transient modifier in Java is used to indicate class fields that should not be serialized when saving an object to a byte stream (for example, when writing to a file or transmitting over a network).

When an object is serialized using ObjectOutputStream, all fields are saved by default except those marked as transient. This is useful for fields that:

  • contain temporary data,
  • should not be saved for security reasons (e.g., passwords),
  • can be restored or recalculated after deserialization.

Example:

import java.io.*;

class User implements Serializable {
    String name;
    transient String password; // will not be serialized

    User(String name, String password) {
        this.name = name;
        this.password = password;
    }
}

// When serialized, password will not be saved

Thus, transient helps control which object data is saved during serialization.

Can you explain the purpose and use of the transient… - sobes.tech