Lesson 3 of 8
Java Serialisation (Serializable & ObjectStream)
Java serialisation converts objects to a byte stream (for saving to disk or sending over a network) and back. The Serializable marker interface enables it; ObjectOutputStream/ObjectInputStream perform it. Serialisation has security implications and a custom form exists with Externalizable.
Serialisation in Practice
import java.io.*;
import java.nio.file.*;
import java.util.List;
// Serializable is a marker interface (no methods)
public class Book implements Serializable {
// serialVersionUID - identifies class version for deserialization
// If class changes and serialVersionUID doesn't match, InvalidClassException thrown
@Serial
private static final long serialVersionUID = 1L;
private final String isbn;
private String title;
private double price;
// transient fields are NOT serialised (excluded from byte stream)
private transient String cachedSummary; // computed, not worth persisting
private transient Object lock; // not serialisable
public Book(String isbn, String title, double price) {
this.isbn = isbn; this.title = title; this.price = price;
}
// Getters...
public String getIsbn() { return isbn; }
public String getTitle() { return title; }
}
public class SerializationDemo {
// Write objects to file
public static void saveBooks(List<Book> books, Path file) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(file)))) {
oos.writeObject(books); // serialise the entire List
}
}
// Read objects from file
@SuppressWarnings("unchecked")
public static List<Book> loadBooks(Path file) throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(
new BufferedInputStream(Files.newInputStream(file)))) {
return (List<Book>) ois.readObject(); // deserialise
}
}
// ❌ Dangers of serialisation:
// 1. Security: malicious byte streams can execute arbitrary code during deserialisation
// → Always validate input before deserialising untrusted data
// 2. Versioning: class changes may break existing serialised files
// → Use serialVersionUID and document the format
// 3. Performance: Java's built-in serialisation is slow and verbose
// → Prefer JSON (Jackson) or Protocol Buffers for most production use
public static void main(String[] args) throws Exception {
List<Book> books = List.of(
new Book("001", "Clean Code", 39.99),
new Book("002", "Effective Java", 44.99)
);
Path file = Path.of("books.ser");
saveBooks(books, file);
System.out.println("Saved " + Files.size(file) + " bytes");
List<Book> loaded = loadBooks(file);
loaded.forEach(b -> System.out.println(b.getTitle()));
}
}Quick Quiz
Tip
Tip
Practice Java Serialisation Serializable ObjectStream in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Java Serialisation (Serializable & ObjectStream)
Practice Task
Note
Practice Task - (1) Write a working example of Java Serialisation Serializable ObjectStream from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Java Serialisation Serializable ObjectStream is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?