Java Object Streams
Serialization and Deserialization
Byte streams write bytes, and character streams write text. But a running program works with objects — a Student with a name and a list of scores, a shopping cart with items. To save an object to a file or send it over a network, it must be converted into a sequence of bytes, and later converted back.
- Serialization turns an object, and every object it refers to, into bytes.
- Deserialization rebuilds equivalent objects from those bytes.
Java has a built-in mechanism for this, used through two stream classes:
| Class | Purpose |
|---|---|
ObjectOutputStream | Wraps an OutputStream; writeObject(obj) serializes an object |
ObjectInputStream | Wraps an InputStream; readObject() deserializes the next object |
They work with any byte stream — a file, a ByteArrayOutputStream in memory, a socket. Classes such as ArrayList, HashMap, String, Integer, LocalDate and Instant already support serialization.
Built-in serialization is still found in older systems (RMI, some caches and session stores, Java desktop applications), so you need to understand it. But it has serious security and maintenance drawbacks, explained in this lesson, and new code usually saves data in explicit formats such as JSON, a database, or Protocol Buffers instead.
Making a Class Serializable
import java.io.*;
import java.util.*;
public class S1 {
static class Student implements Serializable {
private static final long serialVersionUID = 1L;
static String school = "GOCOURSE";
private final String name;
private final List<Integer> scores;
private transient String sessionToken;
private transient int cachedTotal;
Student(String name, List<Integer> scores, String token) {
this.name = name;
this.scores = new ArrayList<>(scores);
this.sessionToken = token;
this.cachedTotal = scores.stream().mapToInt(Integer::intValue).sum();
}
@Override public String toString() {
return name + " " + scores + " token=" + sessionToken + " cachedTotal=" + cachedTotal;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s = new Student("Asha", List.of(91, 85, 78), "eyJhbGciOi...");
System.out.println("before: " + s);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
out.writeObject(s);
}
System.out.println("file size: " + new File("student.ser").length() + " bytes");
Student.school = "changed";
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student copy = (Student) in.readObject();
System.out.println("after: " + copy);
System.out.println("same object? " + (copy == s) + ", school: " + Student.school);
}
}
}
Output:
before: Asha [91, 85, 78] token=eyJhbGciOi... cachedTotal=254
file size: 245 bytes
after: Asha [91, 85, 78] token=null cachedTotal=0
same object? false, school: changed
What each part does:
implements Serializablemarks the class as serializable.Serializableis a marker interface — it has no methods. It's a deliberate opt-in: without it,writeObjectrefuses the object, because converting an object's private state to bytes is a decision the class's author must make.serialVersionUIDis a version number for the class's serialized form. It's explained in detail below.writeObject(s)writes the object's class description and the values of its non-static, non-transient fields, following references to other objects (here, theArrayListand itsIntegers). The 245 bytes include class names and field names, not just the data.readObject()returnsObject, so the result must be cast. It throwsClassNotFoundExceptionif the class of a stored object isn't available in the reading program.- The result is a new object with equal field values — not the original (
copy == sisfalse). transientfields are skipped. After deserialization they have their default values:nullfor objects,0for numbers,falsefor booleans. Usetransientfor data that must not be stored (the session token — a secret) or that can be recalculated (the cached total).staticfields are never serialized, because they belong to the class, not to the object. The reader sees whatever value the static field currently has in its own JVM, here"changed".
During deserialization, the constructor of a serializable class is not called; fields are restored directly from the stream. (The no-argument constructor of the first non-serializable superclass is called, and that class must have one.)
Every Referenced Object Must Be Serializable
import java.io.*;
public class S2 {
static class Logger { }
static class Order implements Serializable {
String id = "ORD-1001";
Logger log = new Logger();
}
public static void main(String[] args) throws IOException {
try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {
out.writeObject(new Order());
} catch (NotSerializableException e) {
System.out.println("NotSerializableException: " + e.getMessage());
}
}
}
Output:
NotSerializableException: S2$Logger
Serialization saves the whole object graph. Order is serializable, but its log field refers to a Logger, which isn't, so writing fails at runtime with NotSerializableException naming the offending class. The usual fixes:
- mark the field
transient(loggers, database connections, threads and open streams shouldn't be serialized anyway — they represent live resources that can't be restored from bytes), or - make the referenced class serializable, if its data really belongs in the saved state.
Object Graphs, Shared References and Cycles
import java.io.*;
import java.util.*;
public class S3 {
static class Course implements Serializable {
String title;
List<Course> prerequisites = new ArrayList<>();
Course(String title) { this.title = title; }
}
public static void main(String[] args) throws Exception {
Course basics = new Course("Java Basics");
Course oop = new Course("OOP");
Course collections = new Course("Collections");
oop.prerequisites.add(basics);
collections.prerequisites.add(basics);
collections.prerequisites.add(oop);
basics.prerequisites.add(collections); // a cycle, just to show it is handled
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(List.of(oop, collections));
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
@SuppressWarnings("unchecked")
List<Course> copy = (List<Course>) in.readObject();
Course oop2 = copy.get(0), col2 = copy.get(1);
System.out.println("shared 'Java Basics' is one object: " + (oop2.prerequisites.get(0) == col2.prerequisites.get(0)));
System.out.println("cycle restored: " + (oop2.prerequisites.get(0).prerequisites.get(0) == col2));
System.out.println("new objects: " + (oop2 != oop));
}
}
}
Output:
shared 'Java Basics' is one object: true
cycle restored: true
new objects: true
ByteArrayOutputStreamandByteArrayInputStreamserialize into memory instead of a file — handy for tests and for making deep copies.- Within one stream, each object is written once. Later references to it are written as a back-reference, so after reading,
Java Basicsis still a single object shared by both courses, exactly as in the original graph. - Cycles (
basics → collections → basics) are handled the same way; naive serializers that just follow references would loop forever. - The
(List<Course>)cast is unchecked, because the compiler can't verify the list's element type at runtime;@SuppressWarnings("unchecked")on the local variable documents that this is intended.
A related trap: if you write the same object twice to the same stream after changing it, the second write is only a back-reference, so the reader sees the old values. Call out.reset() between writes, or use a new stream, when sending updated versions of the same object.
serialVersionUID and Class Changes
Serialized data is often read by a later version of the program than the one that wrote it. serialVersionUID tells Java whether the stored data and the current class are compatible.
Suppose version 1 of a class wrote a file:
public class Profile implements Serializable {
private static final long serialVersionUID = 1L;
String name = "Asha";
}
If version 2 changes the UID to 2L (and adds a field), reading the old file fails:
InvalidClassException: Profile; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
If version 2 keeps serialVersionUID = 1L and adds a field, the old file loads successfully:
public class Profile implements Serializable {
private static final long serialVersionUID = 1L;
String name;
String city = "Chennai";
@Override public String toString() { return "Profile[name=" + name + ", city=" + city + "]"; }
}
Profile[name=Asha, city=null]
Two lessons from this:
- Always declare
serialVersionUIDexplicitly. If you don't, Java computes one from the class's structure (its name, fields, methods and more). Almost any change — even adding a method — or a different compiler can change the computed value, making all existing data unreadable withInvalidClassException. With an explicit value, you decide when a change is incompatible, by changing the number. - Field initializers don't run during deserialization.
cityisnull, not"Chennai", because the constructor and initializers aren't executed. Fields missing from old data get default values. Code that relies on invariants established in a constructor must re-check them after deserialization (for example in a privatereadObjectmethod).
Adding or removing fields is a compatible change; changing a field's type or making a class non-serializable is not. Because the serialized form exposes private fields, it effectively becomes part of the class's public contract — one reason serialization makes classes harder to evolve.
Records and Serialization
Records (Java 16+) can implement Serializable too, and they are handled more safely than ordinary classes: on deserialization, the record's canonical constructor is called with the stored component values. Validation in a compact constructor therefore also protects data read from a stream, which closes one of the classic loopholes of serialization. Records are a good choice when you do use Java serialization; the practical example below uses one.
Security: Never Deserialize Untrusted Data
readObject() can instantiate any serializable class on the classpath, and the bytes decide which. Attackers have built byte sequences (so-called gadget chains) that, while being deserialized, trigger code in commonly used libraries and end up running arbitrary commands. Deserialization of untrusted input has caused many critical vulnerabilities in real servers.
Rules:
- Never call
readObject()on bytes from an untrusted source — HTTP requests, cookies, uploaded files, message queues accessible to others. - If you must, restrict what can be deserialized with an
ObjectInputFilter(Java 9+), which accepts or rejects each class and limits the size and depth of the graph:
import java.io.*;
import java.util.*;
public class Filter {
record CartItem(String sku, int qty) implements Serializable {
CartItem {
if (qty <= 0) throw new IllegalArgumentException("qty must be positive: " + qty);
}
}
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(new ArrayList<>(List.of(new CartItem("PEN-01", 2))));
out.writeObject(new java.util.Date(0));
}
ObjectInputFilter onlyCart = ObjectInputFilter.Config.createFilter(
"java.util.ArrayList;Filter$CartItem;java.lang.*;maxdepth=5;maxrefs=1000;!*");
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
in.setObjectInputFilter(onlyCart);
System.out.println("allowed: " + in.readObject());
System.out.println("allowed: " + in.readObject());
} catch (InvalidClassException e) {
System.out.println("blocked: " + e.getMessage());
}
}
}
Output:
allowed: [CartItem[sku=PEN-01, qty=2]]
blocked: filter status: REJECTED
- The filter pattern is a semicolon-separated list. Class names (with
*wildcards) are allowed;!*at the end rejects everything else, making it an allow-list.maxdepthandmaxrefslimit how deep and how large the object graph can be, which also prevents memory-exhaustion attacks. - The cart list is allowed. The
Dateisn't on the list, so reading it fails withInvalidClassExceptionbefore anyDateobject is created. - An application-wide filter can be set with the system property
-Djdk.serialFilter=....
An allow-list is much safer than trying to block known-dangerous classes, because new gadget chains keep being discovered.
Practical Example: Autosaving a Draft
An editor saves the user's draft periodically and restores it on the next start. The data is written and read only by the same application, on the user's own machine — the kind of situation where Java serialization can still be reasonable — and the code is written defensively: an atomic save, an allow-list filter, and graceful handling of a missing or damaged file.
import java.io.*;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
public class Drafts {
record Draft(String title, List<String> paragraphs, Instant savedAt) implements Serializable {
private static final long serialVersionUID = 1L;
Draft {
Objects.requireNonNull(title, "title");
paragraphs = List.copyOf(paragraphs);
}
}
static final ObjectInputFilter FILTER = ObjectInputFilter.Config.createFilter(
"Drafts$Draft;java.time.Instant;java.time.Ser;java.util.CollSer;java.util.ImmutableCollections$*;"
+ "java.lang.String;java.lang.Object;maxdepth=10;maxbytes=1000000;!*");
static void save(Path file, Draft draft) throws IOException {
Path tmp = file.resolveSibling(file.getFileName() + ".tmp");
try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(tmp)))) {
out.writeObject(draft);
}
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
static Optional<Draft> load(Path file) {
try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(file)))) {
in.setObjectInputFilter(FILTER);
return Optional.of((Draft) in.readObject());
} catch (NoSuchFileException e) {
return Optional.empty();
} catch (IOException | ClassNotFoundException | ClassCastException e) {
System.out.println(" ignoring unreadable draft: " + e.getClass().getSimpleName());
return Optional.empty();
}
}
public static void main(String[] args) throws IOException {
Path file = Path.of("lesson-145.draft");
System.out.println("first start: " + load(file));
Draft d = new Draft("Object Streams", List.of("What serialization is", "transient fields"),
Instant.parse("2026-11-15T04:10:00Z"));
save(file, d);
Draft restored = load(file).orElseThrow();
System.out.println("restored: " + restored.title() + " " + restored.paragraphs() + " saved " + restored.savedAt());
System.out.println("equal: " + restored.equals(d));
Files.write(file, new byte[] {1, 2, 3, 4});
System.out.println("after corruption: " + load(file));
}
}
Output:
first start: Optional.empty
restored: Object Streams [What serialization is, transient fields] saved 2026-11-15T04:10:00Z
equal: true
ignoring unreadable draft: StreamCorruptedException
after corruption: Optional.empty
Step by step:
- The record validates its title, and
List.copyOfmakes the paragraph list immutable. Because records are deserialized through their canonical constructor, these checks also run when a draft is loaded. - Saving is atomic. The object is written to
lesson-145.draft.tmpand then moved over the real file (the pattern from the Write Files lesson), so a crash during autosave never leaves a half-written draft. TheBufferedOutputStreammatters here:ObjectOutputStreamperforms many small writes. - Loading uses an allow-list filter. It lists exactly the classes a
Draftcontains. Some are JDK implementation classes that you wouldn't guess:List.copyOfreturns an internalImmutableCollectionslist that is serialized through a proxy classjava.util.CollSer(with anObject[]inside, which the filter checks as its element typejava.lang.Object), andInstantis serialized throughjava.time.Ser. To find such names for your own classes, install a temporary filter that printsinfo.serialClass()for each class and returnsStatus.UNDECIDED, then copy the names into the pattern. - No saved draft is a normal situation on the first start:
NoSuchFileExceptionbecomes an emptyOptional. - A damaged or incompatible file — corrupted bytes (
StreamCorruptedException), a class version change (InvalidClassException), a rejected class or an unexpected type — is reported and ignored, so the editor still starts with an empty document instead of crashing.
If the draft format needed to be read by other programs, edited by hand or kept compatible over many application versions, a JSON file would be the better choice. The structure of the code — atomic save, validated load, clear fallback — would stay the same.