Introduction & Syntax
Serialization · Study material
Serialization turns a Java object – together with every object it refers to – into a stream of bytes; deserialization rebuilds an equivalent object from those bytes. That lets you save objects to a file, send them over a network, store them in a cache or a session, or make deep copies. Java's built-in mechanism needs only a marker interface, Serializable, plus ObjectOutputStream.writeObject and ObjectInputStream.readObject, but doing it well means understanding transient fields, serialVersionUID and class evolution, how shared references and cycles are preserved, what happens with non-serializable parents and fields, custom writeObject/readObject, keeping singletons single with readResolve, the Externalizable alternative, and how records and enums are handled. Equally important today is security: deserializing untrusted data is a well-known attack vector, which is why filters and formats such as JSON are preferred for external data. This page covers all of it with runnable programs. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.
On this page
- Serializable, ObjectOutputStream and ObjectInputStream
- transient and static fields
- Object graphs: shared references and cycles
- NotSerializableException and non-serializable parents
- Custom writeObject / readObject; readResolve; Externalizable
- serialVersionUID, records, enums, security and alternatives
Serializing and deserializing an object
A class opts in by implementing Serializable. writeObject writes the object's class description and the values of its non-transient instance fields; readObject creates a new object without calling its constructor and fills in the fields. The result has the same state but is a different object.
import java.io.*;
import java.time.LocalDate;
class Student implements Serializable { // Serializable is a marker interface – no methods
private static final long serialVersionUID = 1L; // version of the class's serialized form
private final String name;
private final int roll;
private final LocalDate joined; // LocalDate is Serializable too
Student(String name, int roll, LocalDate joined) { this.name = name; this.roll = roll; this.joined = joined; }
@Override public String toString() { return roll + ":" + name + " (" + joined + ")"; }
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
Student s = new Student("Asha", 101, LocalDate.of(2025, 7, 1));
byte[] data = save(s); // object → bytes (could go to a file, socket, cache …)
Student copy = (Student) load(data); // bytes → a NEW object with the same state
System.out.println(copy);
System.out.println((copy == s) + " " + copy.getClass().getSimpleName() + " " + (data.length > 0));
System.out.println("starts with magic 0xACED: " + ((data[0] & 0xFF) == 0xAC && (data[1] & 0xFF) == 0xED));
}
}
101:Asha (2025-07-01) false Student true starts with magic 0xACED: true
transient and static fields
A transient field is skipped: after deserialization it holds its default value (null, 0, false) – even field initialisers do not run. Static fields belong to the class, not the object, so they are never serialized. Mark passwords, caches, connections, loggers and other derived or non-serializable state as transient.
import java.io.*;
class Session implements Serializable {
private static final long serialVersionUID = 1L;
static int created = 0; // static: belongs to the class – never serialized
final String user;
transient String password; // transient: skipped – comes back as null
transient int loginCount = 5; // comes back as 0 (field initialisers do NOT run)
final int level;
Session(String user, String password, int level) { this.user = user; this.password = password; this.level = level; created++; }
@Override public String toString() { return user + "/" + password + "/" + loginCount + "/" + level; }
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
Session s = new Session("asha", "secret123", 3);
byte[] data = save(s);
Session.created = 99; // change the static value after saving
Session back = (Session) load(data); // no constructor runs for a Serializable class
System.out.println(s);
System.out.println(back);
System.out.println("created = " + Session.created);
}
}
asha/secret123/5/3 asha/null/0/3 created = 99
Object graphs
Serialization follows references recursively, so a whole graph is saved. Each object is written only once per stream; later references become back-references. That is why shared objects stay shared and cycles do not cause infinite loops.
import java.io.*;
import java.util.ArrayList;
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
final String name;
Employee manager; // references are followed and serialized too
Employee(String name) { this.name = name; }
}
class Team implements Serializable {
private static final long serialVersionUID = 1L;
final ArrayList<Employee> members = new ArrayList<>();
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
Employee boss = new Employee("Meena");
Employee a = new Employee("Asha"), r = new Employee("Ravi");
a.manager = boss; r.manager = boss; boss.manager = boss; // shared reference AND a cycle
Team t = new Team();
t.members.add(a); t.members.add(r); t.members.add(boss);
Team copy = (Team) load(save(t));
Employee ca = copy.members.get(0), cr = copy.members.get(1), cb = copy.members.get(2);
System.out.println(ca.name + "->" + ca.manager.name + " " + cr.name + "->" + cr.manager.name);
System.out.println("shared manager kept: " + (ca.manager == cr.manager) + ", is the boss object: " + (ca.manager == cb));
System.out.println("cycle kept: " + (cb.manager == cb) + ", different from original: " + (cb != boss));
}
}
Asha->Meena Ravi->Meena shared manager kept: true, is the boss object: true cycle kept: true, different from original: true
NotSerializableException
Every object reachable through non-transient fields must be serializable, otherwise writeObject throws NotSerializableException naming the offending class. Mark such fields transient (and re-create them after loading) or make their class serializable.
import java.io.*;
class Logger { // NOT Serializable
void log(String m) { }
}
class OrderService implements Serializable {
private static final long serialVersionUID = 1L;
String name = "orders";
Logger logger = new Logger(); // a non-serializable field breaks serialization
}
class SafeService implements Serializable {
private static final long serialVersionUID = 1L;
String name = "orders";
transient Logger logger = new Logger(); // fix: transient (re-create it after loading)
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
try {
save(new OrderService());
} catch (NotSerializableException e) {
System.out.println("NotSerializableException: " + e.getMessage());
}
SafeService s = (SafeService) load(save(new SafeService()));
System.out.println(s.name + " " + (s.logger == null));
try {
save(new Object());
} catch (NotSerializableException e) {
System.out.println("plain Object: " + e.getMessage());
}
}
}
NotSerializableException: Logger orders true plain Object: java.lang.Object
Inheritance
A subclass of a serializable class is serializable. If a serializable class has a non-serializable parent, the parent's fields are not saved; on deserialization the parent's accessible no-arg constructor runs to initialise them (and it must exist).
import java.io.*;
class Person { // NOT Serializable – needs an accessible no-arg constructor
String name = "unknown";
Person() { System.out.println(" Person() runs"); }
Person(String name) { this.name = name; }
}
class Customer extends Person implements Serializable {
private static final long serialVersionUID = 1L;
int points;
Customer(String name, int points) { super(name); this.points = points; System.out.println(" Customer(..) runs"); }
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
System.out.println("creating:");
Customer c = new Customer("Asha", 250);
byte[] data = save(c);
System.out.println("loading:");
Customer back = (Customer) load(data);
System.out.println(back.name + " " + back.points);
// Fields of the serializable class are restored; the non-serializable parent is rebuilt with its no-arg constructor
}
}
creating: Customer(..) runs loading: Person() runs unknown 250
Custom serialization
Private methods writeObject(ObjectOutputStream) and readObject(ObjectInputStream) let a class control its serialized form: call defaultWriteObject/defaultReadObject for the normal fields, then write or read extra data – and validate what you read. The @Serial annotation (Java 14) asks the compiler to check these special methods.
import java.io.*;
class Account implements Serializable {
private static final long serialVersionUID = 1L;
final String id;
transient String pin; // never store it in plain form
transient double balance; // stored in a custom format below
Account(String id, String pin, double balance) { this.id = id; this.pin = pin; this.balance = balance; }
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); // writes the non-transient fields (id)
out.writeLong(Math.round(balance * 100)); // store paise as a long
out.writeUTF(pin == null ? "" : "*".repeat(pin.length())); // only a mask
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
balance = in.readLong() / 100.0;
pin = in.readUTF();
if (balance < 0) throw new InvalidObjectException("negative balance"); // validate what you read
}
}
public class Main {
static byte[] save(Object o) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(o);
}
return bytes.toByteArray();
}
static Object load(byte[] data) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
Account a = (Account) load(save(new Account("SB-101", "4821", 2500.75)));
System.out.println(a.id + " " + a.balance + " " + a.pin);
try {
load(save(new Account("SB-102", "1111", -10)));
} catch (InvalidObjectException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
SB-101 2500.75 **** rejected: negative balance
serialVersionUID
Every serializable class has a version number. If you do not declare one, the JVM computes it from the class's structure, so harmless changes (adding a method) can make old data unreadable with an InvalidClassException. Always declare private static final long serialVersionUID = 1L; and change it only when you deliberately break compatibility. Compatible changes include adding fields (they get default values) and removing fields (old values are ignored).
Externalizable
Externalizable extends Serializable with two methods, writeExternal and readExternal, giving complete control over the format. Unlike Serializable, it requires a public no-arg constructor, which runs before readExternal.
Common mistakes
- Not declaring serialVersionUID.
- Serializing passwords, keys or tokens instead of marking them transient.
- Non-serializable fields (loggers, connections, threads) causing NotSerializableException.
- Expecting constructors or field initialisers to run on deserialization.
- Breaking singletons – add readResolve or use an enum.
- Writing the same changed object twice to one stream – the second write is only a back-reference.
- Deserializing untrusted data without an ObjectInputFilter.
- Using Java serialization for long-term storage or public APIs – prefer JSON, XML or Protocol Buffers.
Key points to remember
- Serializable is a marker interface; writeObject / readObject do the work.
- transient and static fields are not serialized.
- Deserialization creates a new object without calling its constructor (except for records and non-serializable parents).
- Whole object graphs are saved; shared references and cycles are preserved.
- Declare serialVersionUID to control compatibility.
- Use readResolve or enums for singletons; filters for untrusted input.
Frequently asked questions
Why is Serializable a marker interface?
It has no methods; it simply tells the JVM that the class's author allows its objects to be serialized.
Are records serializable?
If they implement Serializable – and they are deserialized through their canonical constructor, so validation always runs.
Is Java serialization still used?
In caches, RMI, some frameworks and legacy systems; new designs usually prefer JSON or binary formats like Protocol Buffers.
Where can I learn more?
Read Java Serialization and Java File Handling, then practise with the exercises below.