Junior — Middle
What is the purpose of the transient modifier in programming?
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, all its fields are saved by default. If a field is marked as transient, it will be skipped, and upon deserialization, this field will receive the default value (null for objects, 0 for numbers, etc.).
Example:
class User implements Serializable {
private String name;
private transient String password; // will not be serialized
// constructors, getters, setters
}
This is useful for protecting sensitive data or for fields that can be reconstructed and do not need to be saved.