Junior
What is the 'transient' keyword in Java?
sobes.tech AI
Answer from AI
The transient keyword in Java is used to indicate that a class field should not be serialized when the object of that class is converted into a byte stream.
Usage:
- Exclusion from serialization: Fields marked as
transientare ignored by standard serialization mechanisms (e.g., usingObjectOutputStream). - Use cases:
- Saving state that can be easily recalculated during deserialization (e.g., cached data).
- Avoiding serialization of confidential information (passwords, tokens).
- Excluding resources that cannot be serialized (e.g., input/output streams).
Example:
import java.io.Serializable;
class User implements Serializable {
private String username;
private transient String password; // This field 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 and setters
}