Why this matters
- A missing
serialVersionUIDis the classic cause of a deployment that fails to read yesterday's cached data. - Deserialising untrusted bytes is one of the most exploited vulnerability classes in Java history, and knowing why is a genuine security skill.
- Even though JSON has replaced it for most purposes, Java serialization still appears in session replication, caches and older RMI-based systems.
The basic mechanism
Implement the marker interface Serializable and the JVM handles the rest.
What is and is not written
- Instance fields are written, including private ones, recursively for referenced objects.
transientfields are skipped and come back as the type's default —null,0,false.staticfields belong to the class, not the object, so they are never part of the stream.- Every referenced object must also be
Serializable, or writing fails withNotSerializableException. - The object graph is preserved. If two fields point at the same object, deserialisation restores one shared object, not two copies.
serialVersionUID
This long is the class's structural fingerprint. It is written into the stream and checked on read.
If you omit it the compiler computes one from the class's fields, methods and modifiers. That sounds
convenient and is a trap: adding a single field changes the computed value, and every previously
written stream becomes unreadable with InvalidClassException.
How changes behave when you declare it explicitly
- Adding a field is compatible. Old streams deserialise with the new field left at its default.
- Removing a field is compatible. The value in the stream is discarded.
- Renaming a field is not compatible in effect — it reads as a removal plus an addition, so the data is silently lost.
- Changing a field's type is incompatible and throws.
- Changing the class hierarchy is incompatible.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 6 sections
- Controlling the process
- Externalizable
- Breaking singletons — and the enum fix
- Records and serialization
- The security problem
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.