How do you serialize an object with circular references in Java?

Java serialization automatically handles circular references by maintaining an internal reference table of objects that have already been serialized. When the serializer encounters an object that has already been processed, it writes a reference to the existing object instead of serializing it again. This prevents infinite recursion and preserves the original object relationships.

Key Points

Example

Consider an Employee object that references a Department, and the Department object also references the same Employee. This creates a circular reference.

import java.io.Serializable;

class Employee implements Serializable {

    String name;
    Department department;
}

class Department implements Serializable {

    String departmentName;
    Employee manager;
}

public class Demo {

    public static void main(String[] args) {

        Employee emp = new Employee();
        Department dept = new Department();

        emp.name = "Amol";
        dept.departmentName = "IT";

        emp.department = dept;
        dept.manager = emp;
    }
}

Object Relationship

Employee

|

    v
Department
    |
    v
Employee

This forms a circular reference.

How Java Handles It

1. Java serializes the Employee object.

2. It encounters the Department object and serializes it.

3. While serializing Department, it encounters Employee again.

4. Since Employee was already serialized, Java stores only a reference to it.

5. Infinite recursion is avoided.

Benefits

Real-World Example

In an organization management system

These interconnected relationships often create circular references, and Java serialization handles them automatically without additional coding.

Interview Tip

A concise interview answer is

Java automatically handles circular references during serialization by tracking objects that have already been serialized. When the same object is encountered again, Java writes a reference to the existing serialized object instead of serializing it repeatedly. This prevents infinite recursion and preserves the complete object graph during deserialization.

Last updated: 1 November 2026

Previous question: Is it possible to serialize static fields in Java? Why or why not?

Next question: What is method overloading in Java?

More Core Java - Level II interview questions

All Core Java - Level II questions