Serialization in Java : Step-by-Step Guide | Updated 2025

Java Serialization: Concepts and Implementation with Examples

CyberSecurity Framework and Implementation article ACTE

About author

Karthick (Web Developer )

Karthick is a Java educator who focuses on object persistence and communication between systems. He specializes in serialization, which is the process of changing object states into byte streams. His knowledge includes the Serializable interface, ObjectOutputStream, and deserialization methods. He teaches how to store, send, and recreate Java objects across different platforms.

Last updated on 12th Sep 2025| 10565

(5.0) | 32961 Ratings

Introduction to Serialization in Java

Serialization is a powerful mechanism in Java that allows objects to be converted into a byte stream. This process enables storage of the object or its transmission over a network, ensuring that the object’s state can be recreated later via deserialization. Java provides built-in support for serialization via the java.io package, making it a critical feature for distributed systems, persistent storage, and remote method invocation. To complement such backend capabilities with practical development expertise, exploring Web Developer Training equips learners with the skills to build secure, scalable web applications covering HTML, CSS, JavaScript, and backend technologies that support data integrity, session management, and cross-platform communication.


To Earn Your Web Developer Certification, Gain Insights From Leading Data Science Experts And Advance Your Career With ACTE’s Web Developer Courses Today!


What is Serialization and Deserialization?

Serialization:

Serialization is the process of converting an object into a sequence of bytes for storage or transmission. Once serialized, an object can be written to a file, stored in a database, or sent over a network. To complement such low-level data handling with structured application development, exploring Java Frameworks Overview introduces powerful tools like Spring, Hibernate, and Struts each offering built-in support for serialization, session management, and scalable architecture across enterprise-grade systems.

Deserialization:

Deserialization is the reverse process, where the byte stream is converted back into a copy of the original object. This enables the re-creation of the object’s exact state at the time of serialization.

Example:

  • ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“data.ser”));
  • out.writeObject(myObject);
  • out.close();
  • ObjectInputStream in = new ObjectInputStream(new FileInputStream(“data.ser”));
  • MyClass obj = (MyClass) in.readObject();
  • in.close();

    Subscribe To Contact Course Advisor

    Importance and Use Cases of Serialization

    Serialization is a core mechanism for:

    • Persistent Storage: Saving object states in files or databases.
    • Distributed Systems: Transmitting objects between machines in RMI or EJB.
    • Caching: Storing computed results for reuse.
    • Session Management: Web applications often serialize user sessions.
    • Deep Cloning: Object copies with exact state replication.

    Serialization enhances portability and state management in applications where object persistence or transmission is required. To complement such data-handling capabilities with structured object-oriented design, exploring Hierarchical Inheritance in C++ reveals how multiple derived classes can inherit from a single base class enabling modular architecture, code reuse, and scalable system behavior across diverse application layers.


    Would You Like to Know More About Web Developer? Sign Up For Our Web Developer Courses Now!


    How Serialization Works in Java

    In Java, serialization is a process that converts an object into a byte stream. This allows you to save the object’s state to a file or send it over a network. To serialize an object, it must implement the Serializable interface. The two main classes for this are ObjectOutputStream and ObjectInputStream, located in the java.io package. To complement such backend serialization techniques with practical development expertise, exploring Web Developer Training equips learners with the skills to build secure, scalable web applications covering HTML, CSS, JavaScript, and backend technologies that support data persistence, API integration, and real-world deployment.

    • class Employee implements Serializable {
    • int id;
    • String name;
    • }

    Now, this Employee object can be serialized and later deserialized using file streams. This makes it easy to store and retrieve complex data in Java applications.

    Course Curriculum

    Develop Your Skills with Web Developer Certification Course

    Weekday / Weekend BatchesSee Batch Details

    java.io.Serializable Interface Explained

    The Serializable interface is a marker interface that does not contain any methods. When a class implements Serializable, it signals to the JVM that its instances can be serialized. To complement such low-level functionality with broader development tools, exploring What Is the Java API introduces developers to a vast collection of prewritten classes and packages covering everything from file handling and networking to data structures and multithreading, all designed to streamline Java application development.

    Features:

    • No methods to override.
    • Ensures compatibility with Java’s serialization mechanism.
    • Required to avoid NotSerializableException.

    If a class contains non-serializable fields (like file handles or sockets), it must manage them using the transient keyword or implement custom serialization logic.


    Are You Interested in Learning More About Web Developer? Sign Up For Our Web Developer Courses Today!


    Transient Keyword and Its Role

    Java provides the transient keyword to mark fields that should not be serialized. This is especially useful for fields containing sensitive data, temporary values, or system-dependent objects. To complement such serialization control with efficient string manipulation, exploring StringBuilder Methods in Java introduces powerful operations like append(), insert(), delete(), and reverse enabling dynamic text construction with better performance and reduced memory overhead compared to immutable String objects.

    Example:

    • class User implements Serializable {
    • String username;
    • transient String password; // Will not be serialized
    • }

    During deserialization, the transient field will be assigned its default value (e.g., null for objects, 0 for integers).

    Web Development Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    SerialVersionUID: Purpose and Usage

    The serialVersionUID is a unique identifier for each serializable class. It verifies compatibility during deserialization. If the UID of the class does not match the UID of the serialized object, the JVM throws an InvalidClassException. To complement such version control mechanisms with compile-time configuration strategies, exploring Preprocessor Directives in C reveals how macros, conditional compilation, and file inclusion directives help manage code complexity, platform-specific logic, and modular development in C-based systems.

    • Prevents deserialization errors when class definitions change.
    • Maintains version control for serialized objects.
    • private static final long serialVersionUID = 1L.

    It is recommended to explicitly define serialVersionUID to maintain consistency across JVM versions and code modifications.

    Custom Serialization Using writeObject() and readObject()

    Sometimes, default serialization is not sufficient especially when:

    • You want to control what data is serialized.
    • Transient or sensitive fields need special handling.
    • Version migration is involved.

    Custom Methods:

    You can override two special methods:

    • private void writeObject(ObjectOutputStream oos) throws IOException {
    • oos.defaultWriteObject();
    • // Custom logic here
    • private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    • ois.defaultReadObject();
    • // Custom logic here
    • }

    This allows fine-grained control over the serialization process.


    Serialization in Java with Inheritance

    The serialVersionUID is a unique identifier for each serializable class. It verifies compatibility during deserialization. If the UID of the class does not match the UID of the serialized object, the JVM throws an InvalidClassException. To complement such version control mechanisms with compile-time configuration strategies, exploring Preprocessor Directives in C reveals how macros, conditional compilation, and file inclusion directives help manage code complexity, platform-specific logic, and modular development in C-based systems.

    • Only the subclass’s state is serialized.
    • The superclass’s constructor will be called during deserialization.
    • If both parent and child are Serializable, all fields are serialized.
    • If the parent class is not Serializable, its constructor is invoked when deserializing.

    Example:

    • class A {
    • int a;
    • }
    • class B extends A implements Serializable {
    • int b;
    • }

    Here, only b is serialized. During deserialization, a will be initialized via A’s constructor.


    Handling Static Members and Object Graphs

    Static Fields:

    Static fields are not serialized, as they belong to the class, not the object. They maintain a single shared state across all instances and are not part of the object’s memory layout. After deserialization, static fields will retain their class-defined values, not serialized state.

    • All referenced objects must implement Serializable.
    • Cyclic dependencies are handled safely.

    Object Graphs

    Java’s serialization is recursive. If an object contains references to other serializable objects, the entire object graph is serialized. If an Employee is also serializable, the whole chain is serialized.


    Serialization Pitfalls and Best Practices

    Common Pitfalls in Serialization:

    • Forgetting serialVersionUID: Causes compatibility issues across versions.
    • Not marking non-serializable fields as transient: Leads to NotSerializableException.
    • Serializing unnecessary data: Wastes bandwidth and storage.
    • Insecure serialization: Deserializing untrusted data can lead to security vulnerabilities.

    Real-World Examples

    • Session Persistence in Web Servers: In servlets, user session objects are serialized to preserve state across server restarts.
    • Remote Method Invocation (RMI): Objects are serialized and transmitted over the network to allow remote communication between Java programs.
    • Database Caching Systems: Serialized objects are stored in cache systems (like Redis or Memcached) for faster retrieval.
    • Mobile Applications: Serialized data is used to persist state between app sessions or save settings locally.
    • Game Development: Game state objects are serialized to allow saving and loading game progress.

    Summary

    Serialization in Java is an important technique that lets developers convert Java objects into byte streams, making it easy to store or transmit them. During this process, deserialization helps recreate the original objects from these byte streams. To make a class serializable, you need to implement the Serializable interface. It’s also important to use the transient keyword for any fields that shouldn’t be serialized. Managing the serialVersionUID is vital for keeping compatibility between different versions of classes. To complement such object serialization practices with practical development expertise, exploring Web Developer Training equips learners with the skills to build robust web applications covering HTML, CSS, JavaScript, and backend technologies that support secure data handling, version control, and scalable architecture. You can also customize the serialization process by overriding the writeObject() and readObject() methods. Serialization works well with inheritance and complex object graphs, but it must be used carefully to avoid potential issues like security vulnerabilities and performance problems.

    Upcoming Batches

    Name Date Details
    Web Developer Certification Course

    08 - Sep- 2025

    (Weekdays) Weekdays Regular

    View Details
    Web Developer Certification Course

    10 - Sep - 2025

    (Weekdays) Weekdays Regular

    View Details
    Web Developer Certification Course

    13 - Sep - 2025

    (Weekends) Weekend Regular

    View Details
    Web Developer Certification Course

    14 - Sep - 2025

    (Weekends) Weekend Fasttrack

    View Details