🔍 1. static
Fields
✅ Summary:
static
fields are never serialized.
Why?
static
means 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:
username
is restored from fileappName
comes from the current loaded class, not the serialized data
🔍 2. final
Fields
✅ Summary:
final
fields are serialized normally — but you can’t change them after deserialization (because they’re final!).
Why?
final
means 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
final
fields 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
username
correctly 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 |