Java Object Serialization: Saving and Loading Objects
Save and restore object graphs with Java serialization: ObjectOutputStream.writeObject, ObjectInputStream.readObject, the Serializable marker interface, shared references and serial numbers, non-serializable superclasses, NotSerializableException, and when to avoid it.
kvi5hnuCode Sprout team member9 min readOn this page
The previous articles stored employee records as text and as fixed-size binary records. That works when all objects have the same type and the same fields. Real object-oriented data is messier. An array declared as Employee[] may hold Manager objects with extra fields, and objects refer to other objects, sometimes shared among several owners. Designing a file format for such graphs is a lot of work. Java has a built-in, general mechanism that does it for you: object serialization. This article covers the basics. The following three articles look at the file format, at customizing the process, and at versioning and security.
Writing and reading objects
To write objects, wrap an ObjectOutputStream around any output stream and call writeObject:
try (var out = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
out.writeObject(omar);
out.writeObject(boss);
}
To read them back, wrap an ObjectInputStream around an input stream and call readObject in the same order. The result is an Object, so cast it:
try (var in = new ObjectInputStream(new FileInputStream("employee.ser"))) {
var e1 = (Employee) in.readObject();
var e2 = (Employee) in.readObject();
}
readObject declares ClassNotFoundException as well as IOException, because the stream names classes that the reading program must be able to load.
Object streams also implement DataOutput and DataInput, so you can mix in primitive values with writeInt, writeDouble and the rest, and read them back with readInt and friends. You can't use writeObject for primitives (they'd be boxed), and you can't use writeInt for objects.
The Serializable interface
There's one requirement: the class of every object you write must implement java.io.Serializable:
class Employee implements Serializable { ... }
Serializable has no methods. It's a marker interface that says "the author of this class allows its objects to be serialized". Subclasses of a serializable class are serializable too. Unlike Cloneable, you don't need to override anything. Behind the scenes, ObjectOutputStream saves the values of all non-static, non-transient fields of the object and its superclasses, recursively following references to other objects.
If any object in the graph isn't serializable, writeObject throws a NotSerializableException naming the offending class. Most library value classes, such as String, the wrappers, LocalDate, BigDecimal and the standard collections, are serializable. Classes that wrap operating system resources, such as Thread, streams and sockets, are not.
You'll see the compiler warning serializable class has no definition of serialVersionUID when compiling with -Xlint. It's about versioning, explained in article 35. The fix is to declare the field, as the demo does:
@Serial
private static final long serialVersionUID = 1L;
The @Serial annotation (Java 14) marks serialization-related members so the compiler can check their declarations.
Shared references and serial numbers
What happens when one object is referenced by several others? In the demo, two managers share the same assistant:
var omar = new Employee("Omar Haddad", ...);
var priya = new Manager("Priya Nair", ...);
priya.setAssistant(omar);
var lena = new Manager("Lena Fischer", ...);
lena.setAssistant(omar);
Memory addresses are meaningless in a file, and an object reloaded later sits somewhere else in memory. Writing Omar's data twice would be wrong too: after reloading, the two managers would have two different secretaries, and raising one assistant's salary wouldn't affect the other.
Serialization solves this by giving each object a serial number, which is where the name comes from:
- The first time the output stream meets an object, it assigns the object a serial number and writes its data.
- Every later time it meets the same object, it writes only "same as object number x".

Reading reverses the process. When an object appears for the first time, the input stream constructs it, fills in its fields and remembers its number. A back-reference returns the object already created. The result is a graph with exactly the same shape as the original, shared objects and cycles included. (The diagram is simplified. The real stream also numbers class descriptors and strings, as the next article shows.)
The serial numbers are scoped to one stream. Within a single ObjectOutputStream, writing the same object twice writes a back-reference the second time, even if the object has changed in between. Call out.reset() to forget the objects written so far, if you deliberately want to write a fresh copy. Reading the same bytes twice through two input streams gives two independent copies.
This mechanism also explains how serialization can transfer object graphs between machines, for example in remote method invocation or in distributed caches: serial numbers replace addresses that would mean nothing on another computer.
Non-serializable superclasses
A serializable class can extend a class that isn't serializable, but that superclass needs an accessible no-argument constructor. During deserialization, the fields of the serializable classes are read from the stream, while the fields of the non-serializable superclass are initialized by running its no-argument constructor. In the demo, Student extends Person. The student's school survives the round trip, but the nickname field declared in Person comes back with the value its constructor gives it, "unset".
Note also that no constructor of a serializable class runs during deserialization. Objects are created without calling Employee's constructors, and their fields are filled in directly from the stream. Records are the exception (article 34).
A complete example
import java.io.*;
import java.time.LocalDate;
import java.util.*;
public class Solution {
static class Employee implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private String name;
private double salary;
private LocalDate startDate;
Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
this.startDate = LocalDate.of(year, month, day);
}
void giveRaise(double pct) { salary += salary * pct / 100; }
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + name + ",salary=" + salary + ",startDate=" + startDate + "]";
}
}
static class Manager extends Employee {
@Serial
private static final long serialVersionUID = 1L;
private Employee assistant;
Manager(String name, double salary, int year, int month, int day) { super(name, salary, year, month, day); }
void setAssistant(Employee assistant) { this.assistant = assistant; }
Employee getAssistant() { return assistant; }
@Override
public String toString() { return super.toString() + "[assistant=" + assistant + "]"; }
}
// a non-serializable superclass needs an accessible no-arg constructor
static class Person {
String nickname = "unset";
Person() { }
}
static class Student extends Person implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
String school;
Student(String nickname, String school) {
this.nickname = nickname;
this.school = school;
}
}
static class Plain { } // doesn't implement Serializable
static byte[] serialize(Object obj) throws IOException {
var bytes = new ByteArrayOutputStream();
try (var out = new ObjectOutputStream(bytes)) {
out.writeObject(obj);
}
return bytes.toByteArray();
}
static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
var omar = new Employee("Omar Haddad", 52000, 2019, 9, 2);
var priya = new Manager("Priya Nair", 91000, 2016, 4, 11);
priya.setAssistant(omar);
var lena = new Manager("Lena Fischer", 46000, 2021, 6, 21);
lena.setAssistant(omar);
Employee[] staff = { priya, omar, lena };
// write several objects and primitive values, then read them back in the same order
var file = java.nio.file.Files.createTempFile("employee", ".ser");
try (var out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file.toFile())))) {
out.writeInt(staff.length);
out.writeObject(staff);
out.writeObject("the end");
}
try (var in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file.toFile())))) {
int n = in.readInt();
var newStaff = (Employee[]) in.readObject();
String trailer = (String) in.readObject();
System.out.println("count " + n + ", trailer \"" + trailer + "\"");
// the shared assistant is still a single object
var newPriya = (Manager) newStaff[0];
var newLena = (Manager) newStaff[2];
System.out.println("same assistant object: " + (newPriya.getAssistant() == newLena.getAssistant()));
System.out.println("and it's newStaff[1]: " + (newPriya.getAssistant() == newStaff[1]));
System.out.println("but a different object from the original: " + (newStaff[1] != omar));
newStaff[1].giveRaise(10);
for (Employee e : newStaff) System.out.println(e);
}
java.nio.file.Files.delete(file);
// the dynamic type is preserved
Object back = deserialize(serialize(new ArrayList<>(List.of(priya))));
System.out.println("read back an " + back.getClass().getSimpleName() + " holding a "
+ ((List<?>) back).get(0).getClass().getSimpleName());
// fields of a non-serializable superclass come from its no-arg constructor
var student = (Student) deserialize(serialize(new Student("Ace", "Riverside High")));
System.out.println("student: school=" + student.school + ", nickname=" + student.nickname);
// objects of classes that aren't Serializable can't be written
try {
serialize(List.of(new Plain()));
} catch (NotSerializableException e) {
System.out.println("NotSerializableException: " + e.getMessage().replaceAll(".*\\$", ""));
}
// reading back an object graph twice gives two separate copies
byte[] once = serialize(omar);
System.out.println("two reads, two objects: " + (deserialize(once) != deserialize(once)));
System.out.println("serialized size of the staff array: " + serialize(staff).length + " bytes");
}
}
count 3, trailer "the end"
same assistant object: true
and it's newStaff[1]: true
but a different object from the original: true
Manager[name=Priya Nair,salary=91000.0,startDate=2016-04-11][assistant=Employee[name=Omar Haddad,salary=57200.0,startDate=2019-09-02]]
Employee[name=Omar Haddad,salary=57200.0,startDate=2019-09-02]
Manager[name=Lena Fischer,salary=46000.0,startDate=2021-06-21][assistant=Employee[name=Omar Haddad,salary=57200.0,startDate=2019-09-02]]
read back an ArrayList holding a Manager
student: school=Riverside High, nickname=unset
NotSerializableException: Plain
two reads, two objects: true
serialized size of the staff array: 377 bytes
After reading, raising newStaff[1]'s salary is visible through both managers' assistant fields, proof that the shared object stayed shared. The objects read back are new objects, distinct from the originals.
Common questions
Should I use serialization to save my application's data, such as a game state? For quick, private data that only your current program version reads, it works. But any change to the classes can make old save files unreadable, and the format cannot be inspected or edited. For files that should survive updates, a documented format such as JSON, XML, or a simple binary format of your own is the better long-term choice.
Java has no JSON API. What do people use? Libraries: Jackson and Gson are the most common, and Jakarta JSON Processing and JSON Binding are the standard APIs in the Jakarta EE world. Records map to JSON nicely with these libraries.
Do records need to implement Serializable?
Yes, records are not serializable by default. Declare record Point(int x, int y) implements Serializable {}. Record serialization is simpler and safer than for ordinary classes, because the canonical constructor runs on deserialization (article 34).
Why can't I serialize a lambda?
A lambda is serializable only if its target interface type is serializable, for example through an intersection cast (Runnable & Serializable) () -> .... Even then it depends on the exact class that defined it. Don't serialize lambdas; store data that describes the behavior instead.
What is the difference between Serializable and Externalizable?
Serializable saves fields automatically, and you can customize the process. Externalizable makes the class write and read its entire state itself and requires a public no-argument constructor. Article 34 compares them.
Is serialization fast? It is reasonably fast for Java-to-Java transfers, but the stream contains a lot of metadata, and reflection is used to access fields. Specialized formats such as Protocol Buffers are smaller and faster, and they work across languages.
API reference
java.io.ObjectOutputStream (implements DataOutput)
| Method | Description |
|---|---|
ObjectOutputStream(OutputStream out) | writes the stream header to out, ready for objects |
void writeObject(Object obj) | writes the object, its class information and all reachable objects not yet written |
void reset() | forgets which objects were written, so they'll be written again in full |
java.io.ObjectInputStream (implements DataInput)
| Method | Description |
|---|---|
ObjectInputStream(InputStream in) | reads and checks the stream header |
Object readObject() | reads the next object and the objects it references; throws ClassNotFoundException if a class can't be found |
java.io.Serializable: a marker interface with no methods.
java.io.Serial (Java 14): an annotation for serialization-related fields and methods such as serialVersionUID.
Summary
ObjectOutputStream.writeObjectsaves an object and everything reachable from it.ObjectInputStream.readObjectrestores it. Read in the same order you wrote.- Classes must implement the marker interface
Serializable. OtherwisewriteObjectthrowsNotSerializableException. - Each object gets a serial number. Repeated references are written as back-references, so shared objects and cycles survive intact.
- Non-serializable superclasses need an accessible no-argument constructor, which initializes their fields on deserialization. Constructors of serializable classes don't run.
- Serialization is Java-specific, fragile under change, and dangerous with untrusted input. Prefer standard formats for long-term storage and data exchange.
Practice Questions
What does a class need to do to become serializable?
Implement java.io.Serializable. It has no methods, so nothing else is required. All its non-static, non-transient fields must also refer to serializable objects or primitives, or writing fails with NotSerializableException. Declaring a serialVersionUID is strongly recommended.
Two Manager objects share one Employee assistant. After serializing and deserializing the managers in one stream, how many assistant objects exist?
One. The assistant is written once and the second reference becomes a back-reference to it, so both deserialized managers point to the same new Employee object.
You write an object, change one of its fields, and write it again to the same ObjectOutputStream. What does the reader get the second time?
The same object as the first time, with the old field value. The second writeObject wrote only a back-reference. Call out.reset() before writing it again if you want the new state written in full.
Class B extends A implements Serializable, and A isn't serializable and has only a constructor A(String). What happens when you deserialize a B?
Deserialization fails with an InvalidClassException ("no valid constructor"), because the fields of a non-serializable superclass must be initialized by an accessible no-argument constructor, and A doesn't have one.
Why is serialization a poor choice for a file format that a web service reads?
It's a Java-specific binary format that other languages can't easily read. It ties the file to the internal fields of your classes, so harmless refactoring can make old files unreadable. And deserializing data that arrives from outside is a serious security risk. JSON, XML or Protocol Buffers are better choices.
Previous: Java File Locking: FileLock, Shared and Exclusive Locks
Next: The Java Serialization File Format: Handles, Class Descriptors and Fingerprints
Related reading
- Java File Locking: FileLock, Shared and Exclusive Locks
- Java NIO Buffers: Capacity, Position, Limit, flip and compact
- Java Memory-Mapped Files: FileChannel.map and Performance
- Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
- Java Files: Copying, Moving, Deleting and Reading File Attributes

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.