🔍 1. static Fields
✅ Summary:
staticfields are never serialized.
Why?
staticmeans the field belongs to the class itself, not to any specific object.- Serialization is all about saving the state of an object — and static fields are shared across all instances.
💡 So when you serialize an object, its static fields are ignored.
🔧 Example:
public class User implements Serializable {
static String appName = "MyApp"; // static — shared across all
String username;
}
Serialization ignores appName.
After deserialization:
usernameis restored from fileappNamecomes from the current loaded class, not the serialized data
🔍 2. final Fields
✅ Summary:
finalfields are serialized normally — but you can’t change them after deserialization (because they’re final!).
Why?
finalmeans the field cannot be reassigned.- It will be serialized, just like any normal field.
- During deserialization, Java uses low-level memory allocation (bypassing constructors), so even
finalfields can be set internally.
🔧 Example:
public class User implements Serializable {
final String username; // final — not changeable
public User(String username) {
this.username = username;
}
}
This will:
- Serialize
username - Restore
usernamecorrectly during deserialization - But you can’t reassign it — because it’s final.
✅ Yes, Java can set final fields during deserialization!
🔥 Bonus: static final
Fields like:
static final String VERSION = "1.0";
✅ Act like constants (inlined at compile time)
❌ Not serialized
Used at class level, not object level
🧵 TL;DR
| Modifier | Serialized? | Why / Effect |
|---|---|---|
static | ❌ No | Belongs to class, not instance |
final | ✅ Yes | Immutable, but still part of the object |
static final | ❌ No | Constant, compile-time inlined |