The transient
keyword in Java is used to indicate that a field should not be serialized when an object is converted into a byte stream (for example, when saving to a file, sending over a network, or caching).
Why use transient
?
When an object implements Serializable
, all its fields are serialized by default — meaning they are saved as part of the object’s state. However, sometimes you don’t want certain fields to be saved. This could be because:
- The field contains sensitive information (like passwords).
- The field is derived (can be recalculated and doesn’t need to be stored).
- The field holds temporary data (like a cache or connection to a database/socket).
- The field refers to a resource that cannot be meaningfully serialized, such as file handles, threads, or other transient system resources.
Example
import java.io.Serializable;
public class User implements Serializable {
private String username;
private transient String password; // this will NOT be serialized
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{username='" + username + "', password='" + password + "'}";
}
}
If you serialize and deserialize this object, the username
will be restored, but the password
will be lost (it will be null
after deserialization).
Key point
transient
only affects serialization. It has no effect on normal object usage, copying, or reflection. It is strictly tied to the Serializable
mechanism.
Quick analogy
Think of transient
as a “do not pack this” sticker when you’re preparing luggage for a flight. The object gets “packed” (serialized), but anything marked transient
stays behind.