Skip to main content
PreparationZone Logo
PrepZone

Serialization

Turning objects into bytes, the role of serialVersionUID and transient, and the security caveat.

Pass checkpoint below

Why this matters

  • A missing serialVersionUID is 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.
Binary data
InputStream / OutputStreamImages, PDFs, audio
BufferedInputStreamReads in blocks
Text data
Reader / WriterHandles character encoding
BufferedReaderGives you readLine()
Pick the family by data type, then wrap a buffer around it. Buffering is what turns thousands of tiny system calls into a handful of big ones.

The basic mechanism

Implement the marker interface Serializable and the JVM handles the rest.

Java
Loading compiler…
Java
Loading compiler…

What is and is not written

  • Instance fields are written, including private ones, recursively for referenced objects.
  • transient fields are skipped and come back as the type's default — null, 0, false.
  • static fields 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 with NotSerializableException.
  • 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.

Java
Loading compiler…

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.