Sobes.tech
Junior

What does the keyword 'transient' mean in Java?

sobes.tech AI

Answer from AI

The keyword transient is used to exclude a field from the serialization process. This means that when an object's state is saved to a stream or file, fields marked as transient will not be saved. During subsequent deserialization of the object, these fields will be initialized with default values (e.g., null for objects, 0 for numeric types, false for boolean).

Using transient is useful for fields that:

  • contain sensitive information that should not be saved.
  • are derived from other fields and can be recalculated if necessary.
  • represent resources that are not serializable (e.g., streams, network sockets).

Example:

// Example of using transient
import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private transient String password; // Password will not be serialized
    private int age;

    public User(String username, String password, int age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    // Getters (for example)
    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public int getAge() {
        return age;
    }
}

When serializing a User object, the password field will be ignored. Upon deserialization, the password field will have the value null.