Java Object Streams

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 145 of 306

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:

ClassPurpose
ObjectOutputStreamWraps an OutputStream; writeObject(obj) serializes an object
ObjectInputStreamWraps 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:

  1. implements Serializable marks the class as serializable. Serializable is a marker interface — it has no methods. It's a deliberate opt-in: without it, writeObject refuses the object, because converting an object's private state to bytes is a decision the class's author must make.
  2. serialVersionUID is a version number for the class's serialized form. It's explained in detail below.
  3. writeObject(s) writes the object's class description and the values of its non-static, non-transient fields, following references to other objects (here, the ArrayList and its Integers). The 245 bytes include class names and field names, not just the data.
  4. readObject() returns Object, so the result must be cast. It throws ClassNotFoundException if the class of a stored object isn't available in the reading program.
  5. The result is a new object with equal field values — not the original (copy == s is false).
  6. transient fields are skipped. After deserialization they have their default values: null for objects, 0 for numbers, false for booleans. Use transient for data that must not be stored (the session token — a secret) or that can be recalculated (the cached total).
  7. static fields 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
  • ByteArrayOutputStream and ByteArrayInputStream serialize 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 Basics is 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:

  1. Always declare serialVersionUID explicitly. 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 with InvalidClassException. With an explicit value, you decide when a change is incompatible, by changing the number.
  2. Field initializers don't run during deserialization. city is null, 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 private readObject method).

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. maxdepth and maxrefs limit how deep and how large the object graph can be, which also prevents memory-exhaustion attacks.
  • The cart list is allowed. The Date isn't on the list, so reading it fails with InvalidClassException before any Date object 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:

  1. The record validates its title, and List.copyOf makes the paragraph list immutable. Because records are deserialized through their canonical constructor, these checks also run when a draft is loaded.
  2. Saving is atomic. The object is written to lesson-145.draft.tmp and then moved over the real file (the pattern from the Write Files lesson), so a crash during autosave never leaves a half-written draft. The BufferedOutputStream matters here: ObjectOutputStream performs many small writes.
  3. Loading uses an allow-list filter. It lists exactly the classes a Draft contains. Some are JDK implementation classes that you wouldn't guess: List.copyOf returns an internal ImmutableCollections list that is serialized through a proxy class java.util.CollSer (with an Object[] inside, which the filter checks as its element type java.lang.Object), and Instant is serialized through java.time.Ser. To find such names for your own classes, install a temporary filter that prints info.serialClass() for each class and returns Status.UNDECIDED, then copy the names into the pattern.
  4. No saved draft is a normal situation on the first start: NoSuchFileException becomes an empty Optional.
  5. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Object Streams and get answers drawn from it.

Signed-in readers only.