Object Serialization: Using Transient and serialVersionUID
This topic is part of Java Serialization and explains two important concepts used when serializing objects:

transientkeywordserialVersionUID(Version UID)
Both help control how objects are stored and restored during serialization.
transient Keyword
The transient keyword is used to skip a field during serialization.
Prevents sensitive or unnecessary data from being saved in a serialized file.
Example
import java.io.Serializable;
class User implements Serializable {
String username;
transient String password; // will NOT be serialized
}
When serialized, password will be stored as null (default value).
Why Do We Use transient?
To prevent serialization of:
- Sensitive data (passwords, OTP, tokens)
- Derived values (calculated fields)
- Temporary or cache-like data
- Fields not needed after deserialization
What Happens Without transient?
Without transient, every non-static field is serialized, which may cause:
- Security issues (saving passwords)
- Performance issues (saving unnecessary fields)
- Exceptions (if the field type is not serializable)
Key Points About transient
- Used to exclude fields from serialization
- Static fields are automatically not serialized
- transient + static = still NOT serialized
- Useful for security and performance
serialVersionUID (Object Version Control)
serialVersionUID is a unique identifier for a class that is used during serialization and deserialization.
It ensures that the sender and receiver of a serialized object have the same class structure.
If not, it throws:
InvalidClassException
To avoid this, we define a fixed serialVersionUID.
Example
class Student implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String name;
}
Why Manually Declare serialVersionUID?
If not declared manually:
- JVM auto-generates it based on class structure
- Small changes break compatibility
- Old serialized files become unreadable
Declaring your own ID solves this.
When to Change the serialVersionUID?
Change only when:
- The class structure changes in a way that breaks compatibility
- Old serialized objects should no longer work
Don't change for minor edits like comments, formatting, etc.
Putting It All Together
class Employee implements Serializable {
private static final long serialVersionUID = 100L;
int id;
String name;
transient double salary; // not serialized
}
id,name→ serializedsalary→ skipped
Difference Between transient and serialVersionUID
| Feature | transient | serialVersionUID |
|---|---|---|
| Purpose | Skip field during serialization | Version control of serialized class |
| Applies to | Variables | Class |
| Type | Keyword | Constant long value |
| Effect on Serialization | Field is not saved | Ensures compatibility while saving/loading objects |
| Used For | Security, performance, exclusion | Avoiding class mismatch errors |
