Java Serialization: Serializable, transient, serialVersionUID and Records (OCP 21)
Java serialization for the OCP 21 exam: Serializable, ObjectOutputStream and ObjectInputStream, transient and static fields, serialVersionUID, which constructors run on deserialization, records, custom writeObject/readObject and serialization filters.
kvi5hnuCode Sprout team member10 min readOn this page
Article 88 wrote bytes and text to files. Serialization writes whole objects: their state goes out as a byte stream, and deserialization builds a new object from those bytes later, maybe in another JVM. The exam doesn't ask about the binary format. It asks which classes can be serialized, which fields are saved, and, most of all, what runs and what doesn't when an object is read back.
Making a class serializable
A class opts in by implementing java.io.Serializable. It's a marker interface with no methods. It just gives the serialization machinery permission to read the object's fields.
import java.io.Serial;
import java.io.Serializable;
public class Ticket implements Serializable {
@Serial private static final long serialVersionUID = 1L;
private String event; // saved
private int seat; // saved
private transient String qr; // NOT saved
private static int issued; // NOT saved (belongs to the class, not the object)
}
These are the rules the exam checks:
- The class must implement
Serializable, either directly or through a superclass or a superinterface. If any class in the hierarchy implements it, so do all its subclasses. - Every instance field that gets written must hold a serializable value or
null. A non-serializable object in a non-transient field causes aNotSerializableExceptionat write time, not compile time. Anullfield is fine, because there's nothing to write. transientfields are skipped. On reading they hold their default value (null,0,false), not the value from their initializer.staticfields are never part of the stream. After deserialization a static field just shows whatever the class currently holds.
Most JDK value types are already serializable: String, the wrapper classes, ArrayList, HashMap, the List.of and Map.of collections, LocalDate and enums. Object isn't, and neither are Thread, I/O streams or Optional.
Writing and reading objects
ObjectOutputStream and ObjectInputStream are high-level byte streams, so they wrap another byte stream such as a FileOutputStream or a ByteArrayOutputStream:
try (var out = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(file)))) {
out.writeObject(ticketA);
out.writeObject(ticketB);
}
try (var in = new ObjectInputStream(
new BufferedInputStream(Files.newInputStream(file)))) {
while (true) {
if (in.readObject() instanceof Ticket t) { // returns Object, so check or cast
tickets.add(t);
}
}
} catch (EOFException e) {
// end of the file: the normal exit when the number of objects isn't known
}
Points to remember:
writeObject(Object)accepts any reference at compile time. Whether the object is really serializable is checked when it's written.readObject()returnsObjectand declares bothIOExceptionandClassNotFoundException. The second one is thrown if the class of the stored object isn't on the reader's classpath.- At the end of the stream
readObject()throwsEOFException. It doesn't returnnullor-1. Anullwas written is read back asnull, sonullcan't mark the end. Either catchEOFExceptionor write a count (or a single list) first. - The stream also has
writeInt,writeUTFand similar methods, because these classes implementDataOutput/DataInput. They read back in the same order they were written.
serialVersionUID
Each serializable class has a version number, serialVersionUID, and it's written into the stream. When the stream is read, the stored number must equal the number of the class that's loaded now, or the read fails with InvalidClassException ("local class incompatible").
- Declare it as
private static final long serialVersionUID = 1L;. Strictly, any access modifier works, but it must bestatic final long. - If you don't declare one, the JVM computes a value from the class's structure: name, fields, methods and interfaces. Adding a method or recompiling with a different compiler can change it, so streams written earlier stop being readable. That's why you should declare it yourself.
- Change the number on purpose when a new version of the class really can't read old data.

What runs during deserialization
This is the part the exam likes most. When readObject() rebuilds an ordinary class (not a record):
- Java finds the first superclass that is not
Serializable, often justObject, and runs its no-arg constructor. That constructor must exist and be accessible to the subclass. If it doesn't, the read fails withInvalidClassException: ... no valid constructor. Writing the object still works fine, so the problem only shows up when you read. - For every class in the hierarchy that is
Serializable, no constructor runs, and no instance initializer or field initializer runs either. - Fields of the serializable classes are filled straight from the stream.
transientfields stay at their defaults, even if they're declared with an initializer such as= "calm". - Fields inherited from the non-serializable parent get whatever that parent's no-arg constructor set. They weren't written at all.
class Animal { // not Serializable
protected int kennelId;
Animal() { kennelId = -1; } // runs when a Pet is read back
}
class Pet extends Animal implements Serializable {
private String name;
private transient String mood = "calm";
{ System.out.println("init"); } // does NOT run on read
Pet(String name) { this.name = name; kennelId = 11; }
}
// After a round trip: name restored, mood == null, kennelId == -1
Two more facts:
- Object identity is preserved within one stream. If two objects share a reference, the shared object is written once, and after reading both point to one new copy. Writing the same object twice gives a reference back to the first copy, not a second one.
- Enum constants are written by name and read back as the existing constant, so
==still works.
Customizing serialization
A serializable class can take control of its own format by declaring two private methods with exactly these signatures. The serialization machinery finds them by reflection:
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // writes the non-transient fields as usual
out.writeUTF(encrypt(pin)); // extra data, e.g. a transient field in another form
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject(); // reads them back, in the same order
pin = decrypt(in.readUTF());
}
- If the signature is wrong (public, the wrong parameter, missing
throws), the method is just a normal method and gets ignored. Mark them with@java.io.Serial(Java 14) to document the intent.javac -Xlint:serial(Java 18+) warns about serialization members with the wrong modifiers or signature, such as apublic writeObject. - The data must be read in the same order it was written.
- There are related hooks you may see named:
readResolve()/writeReplace()(swap in a different object) andExternalizable(the class writes everything itself and needs a public no-arg constructor). The OCP 21 objectives only needSerializable,transient,serialVersionUIDand the rules above.
What's current
- Serialization filters. Deserializing untrusted bytes is a well-known security hole, because a crafted stream can create unexpected objects. Java 9 (JEP 290) added
ObjectInputFilter, which can limit classes, depth and array sizes per stream or JVM-wide (jdk.serialFilter). Java 17 (JEP 415) added a filter factory, so each deserialization context can get its own filter. Never deserialize data from a source you don't trust without one. @java.io.Serial(Java 14) marksserialVersionUID,writeObject,readObject,readResolveand similar members sojavaccan check them. Since Java 18,-Xlint:serialalso warns about non-transient fields whose type isn't serializable, as the complete example below shows.- Records (Java 16) are the recommended shape for serialized data: the canonical constructor is the only way in, so invariants always hold.
- For new data formats, most projects use JSON, Protocol Buffers or a similar format instead of Java serialization. Java serialization isn't deprecated and is still on the exam. The JDK team has talked about a future replacement, but nothing has shipped as of Java 25.
Exam traps from this article
A complete example
The program below shows every rule in one run. It writes two pets to a temporary file and reads them back until EOFException. It counts which constructors and initializers ran, and checks transient, static and shared fields. Then it triggers NotSerializableException, rebuilds a record (including a tampered one), fakes a serialVersionUID mismatch by changing the version bytes in the stream, uses custom writeObject/readObject methods, hits the "no valid constructor" failure and round-trips an enum.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class Solution {
static int animalConstructorRuns, petConstructorRuns, petInitializerRuns, tagConstructorRuns;
/** NOT Serializable: its no-arg constructor runs during deserialization. */
static class Animal {
protected int kennelId;
Animal() {
animalConstructorRuns++;
kennelId = -1;
}
}
static class Owner implements Serializable {
@Serial private static final long serialVersionUID = 1L;
final String name;
Owner(String name) { this.name = name; }
}
static class Pet extends Animal implements Serializable {
@Serial private static final long serialVersionUID = 1L;
static String kennelName = "Happy Paws"; // static: never written to the stream
private final String name;
private int age;
private transient String mood = "calm"; // transient: not written
private Owner owner;
{ petInitializerRuns++; }
Pet(String name, int age, Owner owner, int kennelId) {
petConstructorRuns++;
this.name = name;
this.age = age;
this.owner = owner;
this.kennelId = kennelId;
}
@Override
public String toString() {
return name + "(age=" + age + ", mood=" + mood + ", owner=" + (owner == null ? null : owner.name)
+ ", kennelId=" + kennelId + ")";
}
}
/** A record: deserialization goes through the canonical constructor, so validation runs. */
record Tag(String code) implements Serializable {
Tag {
tagConstructorRuns++;
if (code.isBlank()) throw new IllegalArgumentException("blank tag");
}
}
record Collar(String colour) { } // not Serializable
static class Leash { } // not Serializable
static class Walker implements Serializable {
@Serial private static final long serialVersionUID = 1L;
@SuppressWarnings("serial") // javac -Xlint warns: Leash isn't Serializable
Leash leash;
transient Leash spare = new Leash();
}
/** Custom serialization: private writeObject/readObject with exact signatures. */
static class Vet implements Serializable {
@Serial private static final long serialVersionUID = 1L;
private String name;
private transient String pin;
Vet(String name, String pin) { this.name = name; this.pin = pin; }
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // name
out.writeUTF(new StringBuilder(pin).reverse().toString()); // a (weakly) disguised pin
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
pin = new StringBuilder(in.readUTF()).reverse().toString();
}
}
static class Building { // no no-arg constructor
Building(String address) { }
}
static class Shed extends Building implements Serializable {
@Serial private static final long serialVersionUID = 1L;
Shed() { super("yard"); }
}
static byte[] toBytes(Object... objects) throws IOException {
var bytes = new ByteArrayOutputStream();
try (var out = new ObjectOutputStream(bytes)) {
for (Object o : objects) out.writeObject(o);
}
return bytes.toByteArray();
}
static Object fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
return in.readObject();
}
}
static void attempt(String label, Action action) {
try {
System.out.println(" " + label + ": " + action.run());
} catch (IOException | ClassNotFoundException | RuntimeException e) {
System.out.println(" " + label + " -> " + e.getClass().getSimpleName()
+ (e.getMessage() == null ? "" : " (" + e.getMessage().replace("Solution$", "") + ")"));
}
}
interface Action { Object run() throws IOException, ClassNotFoundException; }
public static void main(String[] args) throws Exception {
System.out.println("== 1. Writing objects to a file and reading them back until EOF");
Owner sam = new Owner("Sam");
List<Pet> pets = List.of(new Pet("Biscuit", 3, sam, 11), new Pet("Pepper", 5, sam, 12));
Path file = Files.createTempFile("kennel", ".ser");
try (var out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file.toFile())))) {
for (Pet p : pets) out.writeObject(p);
}
System.out.println(" written: " + pets);
int animalsBefore = animalConstructorRuns, petsBefore = petConstructorRuns, initBefore = petInitializerRuns;
Pet.kennelName = "Changed after writing";
List<Pet> loaded = new ArrayList<>();
try (var in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file.toFile())))) {
while (true) {
Object o = in.readObject(); // null and -1 are NOT end markers here
if (o instanceof Pet p) loaded.add(p);
}
} catch (EOFException endOfFile) {
// normal way to detect the end when the count isn't known
} finally {
Files.delete(file);
}
System.out.println(" read: " + loaded);
System.out.println("\n== 2. What ran during deserialization?");
System.out.println(" Pet constructor: " + (petConstructorRuns - petsBefore) + " times, Pet initializer: "
+ (petInitializerRuns - initBefore) + " times");
System.out.println(" Animal (non-serializable parent) no-arg constructor: "
+ (animalConstructorRuns - animalsBefore) + " times -> kennelId reset to -1");
System.out.println(" transient mood came back as: " + loaded.get(0).mood + "; static kennelName is the current value: "
+ Pet.kennelName);
System.out.println(" both pets still share ONE owner object: " + (loaded.get(0).owner == loaded.get(1).owner)
+ ", but it's a new copy: " + (loaded.get(0).owner != sam));
System.out.println("\n== 3. Every non-transient field must be serializable (or null)");
attempt("Walker with leash = null", () -> toBytes(new Walker()).length > 0);
attempt("Walker with a Leash", () -> { Walker w = new Walker(); w.leash = new Leash(); return toBytes(w).length; });
attempt("a record that doesn't implement Serializable", () -> toBytes(new Collar("red")).length);
System.out.println("\n== 4. Records are rebuilt through the canonical constructor");
byte[] tagBytes = toBytes(new Tag("A-17"));
int tagsBefore = tagConstructorRuns;
attempt("read Tag", () -> fromBytes(tagBytes) + ", constructor runs during read: " + (tagConstructorRuns - tagsBefore));
byte[] tampered = new String(tagBytes, StandardCharsets.ISO_8859_1).replace("A-17", " ")
.getBytes(StandardCharsets.ISO_8859_1);
attempt("read a tampered Tag with a blank code", () -> fromBytes(tampered));
System.out.println("\n== 5. serialVersionUID must match");
byte[] ownerBytes = toBytes(new Owner("Ana"));
byte[] patched = ownerBytes.clone();
byte[] className = Owner.class.getName().getBytes(StandardCharsets.UTF_8);
int at = indexOf(patched, className) + className.length; // the 8-byte UID follows the class name
patched[at + 7] = 2; // pretend it was written by version 2
attempt("same UID", () -> ((Owner) fromBytes(ownerBytes)).name);
attempt("different UID", () -> fromBytes(patched));
System.out.println("\n== 6. Custom writeObject/readObject");
Vet vet = (Vet) fromBytes(toBytes(new Vet("Dr Mira", "4821")));
System.out.println(" name=" + vet.name + ", transient pin restored by readObject: " + vet.pin);
System.out.println("\n== 7. A non-serializable parent needs an accessible no-arg constructor");
byte[] shedBytes = toBytes(new Shed());
System.out.println(" writing a Shed worked: " + (shedBytes.length > 0));
attempt("reading it back", () -> fromBytes(shedBytes));
System.out.println("\n== 8. Enums deserialize to the same constant");
System.out.println(" Thread.State.BLOCKED round trip is the same object: "
+ (fromBytes(toBytes(Thread.State.BLOCKED)) == Thread.State.BLOCKED));
}
static int indexOf(byte[] data, byte[] part) {
outer:
for (int i = 0; i <= data.length - part.length; i++) {
for (int j = 0; j < part.length; j++) if (data[i + j] != part[j]) continue outer;
return i;
}
return -1;
}
}
Output:
== 1. Writing objects to a file and reading them back until EOF
written: [Biscuit(age=3, mood=calm, owner=Sam, kennelId=11), Pepper(age=5, mood=calm, owner=Sam, kennelId=12)]
read: [Biscuit(age=3, mood=null, owner=Sam, kennelId=-1), Pepper(age=5, mood=null, owner=Sam, kennelId=-1)]
== 2. What ran during deserialization?
Pet constructor: 0 times, Pet initializer: 0 times
Animal (non-serializable parent) no-arg constructor: 2 times -> kennelId reset to -1
transient mood came back as: null; static kennelName is the current value: Changed after writing
both pets still share ONE owner object: true, but it's a new copy: true
== 3. Every non-transient field must be serializable (or null)
Walker with leash = null: true
Walker with a Leash -> NotSerializableException (Leash)
a record that doesn't implement Serializable -> NotSerializableException (Collar)
== 4. Records are rebuilt through the canonical constructor
read Tag: Tag[code=A-17], constructor runs during read: 1
read a tampered Tag with a blank code -> InvalidObjectException (blank tag)
== 5. serialVersionUID must match
same UID: Ana
different UID -> InvalidClassException (Owner; local class incompatible: stream classdesc serialVersionUID = 2, local class serialVersionUID = 1)
== 6. Custom writeObject/readObject
name=Dr Mira, transient pin restored by readObject: 4821
== 7. A non-serializable parent needs an accessible no-arg constructor
writing a Shed worked: true
reading it back -> InvalidClassException (Shed; no valid constructor)
== 8. Enums deserialize to the same constant
Thread.State.BLOCKED round trip is the same object: true
Points to notice:
Pet constructor: 0 timesbutAnimal ... 2 times: only the non-serializable parent's no-arg constructor ran, once per pet, sokennelIdcame back as-1rather than 11 or 12.mood=null, even though the field is declared= "calm", because field initializers don't run either.kennelNameshows the value set after writing, since static fields aren't in the stream.- The two pets still share one
Owner, but it's a new object, notsam. Walkerwithleash = nullwrites fine. With a realLeashit fails, and the message names the class. The@SuppressWarnings("serial")is there becausejavac -Xlint:allwarns about this exact field.- The tampered
Tagwas rejected by the record's own compact constructor. Deserialization wrapped theIllegalArgumentExceptionin anInvalidObjectException. - The serialVersionUID sits in the stream as 8 bytes right after the class name. Changing one byte is enough to cause "local class incompatible".
Shedis written without error, and the failure only shows up on reading, becauseBuildinghas no no-arg constructor.
Common questions
Do I have to declare serialVersionUID?
No. Without it, the JVM computes one from the class's structure, but almost any edit to the class changes that number and breaks old data. Declaring it is the recommended practice, and the exam expects you to know why.
Is a subclass of a serializable class serializable too?
Yes. Serializable is inherited like any interface. The reverse case is the tricky one: a serializable subclass of a non-serializable parent is allowed, but the parent's fields aren't saved, and the parent needs an accessible no-arg constructor.
Why are final fields restored if no constructor runs?
Deserialization sets fields directly, below the language level, so even final instance fields get their stored values. A transient final field, though, ends up with its default value. The one exception is a compile-time constant such as = "x": the compiler copies the constant into the code that uses it, so you'd still see "x".
Can I serialize a lambda?
Only if its target type is serializable, for example with a cast like (Runnable & Serializable) () -> .... It's fragile and rarely a good idea. Plain lambdas aren't serializable.
Summary
- Implement
Serializable(a marker interface) and useObjectOutputStream.writeObjectandObjectInputStream.readObject. Cast the result and handleIOExceptionandClassNotFoundException. - Non-transient instance fields must be serializable or
null.transientandstaticfields aren't written, and transient fields come back as defaults. - On reading, only the first non-serializable superclass's no-arg constructor runs. Serializable classes' constructors and initializers are skipped. Records are the exception: their canonical constructor runs.
- Declare
private static final long serialVersionUID. A mismatch givesInvalidClassException. The end of a stream givesEOFException. - Private
writeObject/readObjectwithdefaultWriteObject/defaultReadObjectcustomize the format. Use@Serial, and use serialization filters for untrusted input.
Practice quiz
Test yourself with the serialization quiz: 10 exam-style questions with explanations.
Previous: Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)
Next: Java Console and User Interaction: System.in, System.out, System.err and Console (OCP 21)
Related reading
- Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)
- Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)
- Java Files: Copying, Moving, Deleting and Comparing Files (OCP 21)
- Java Path Methods: normalize, resolve, relativize and Files Basics (OCP 21)
- Java File and Path: Creating Paths and Converting Between Them (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.