What is Serialization in Java: A Beginner’s Guide

Mehul Patel
Mehul Patel
what is serialization in java

Ever wondered how Java saves objects for later use or transfers them across networks? That’s where serialization comes in. It’s a powerful concept every Java developer should know.

Java Serialization is the process of converting an object into a byte stream, so it can be saved to a file or sent over a network, and later reconstructed back into the same object. It plays a major role in data storage, caching, and communication.

If you’re working on a complex project or need help implementing it right, it’s smart to hire expert Java developers who understand serialization in depth. Let’s start by understanding what serialization is in Java and how to implement it step by step.

What is Serialization in Java?

Serialization is the process of converting a Java object into a sequence of bytes, making it easier to save the object to a file or transmit it over a network. Deserialization is the reverse process, where those bytes are used to reconstruct the original object.

Why use serialization:

  • Persistence: Store an object’s state on disk.
  • Communication: Transfer objects across a network.
  • Caching: Save pre-processed objects for quick reuse.

Java’s built-in serialization mechanism relies on the ObjectOutputStream and ObjectInputStream classes from the java.io package to handle these conversions.

How to Implement Serialization in Java?

Java Serialization mainly involves the Serializable interface and two important classes: ObjectOutputStream and ObjectInputStream.

If you’re using Java frameworks like Spring or Hibernate, serialization happens behind the scenes. For example, when objects are stored in sessions or sent over REST APIs. Here’s the basic process, along with examples to help you understand how it works.

Step 1: Implement the Serializable Interface

To make a class serializable, it must implement the java.io.serializable interface. This is a marker interface, meaning it has no methods to override; it simply tells the JVM that the object can be serialized.

import java.io.Serializable;
class Student implements Serializable {
    int id;
    String name;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

Step 2: Serialize the Object Using ObjectOutputStream

You can serialize the object using the writeObject() method of the ObjectOutputStream class. This writes the object’s state to a file or output stream.

import java.io.*;
public class SerializeExample {
    public static void main(String[] args) throws IOException 
        Student s = new Student(101, "Alice");
        FileOutputStream fileOut = new FileOutputStream("student.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(s);
        out.close();
        fileOut.close();
    }
}

Step 3: Deserialize the Object Using ObjectInputStream

To reconstruct the object from the byte stream, use the readObject() method of the ObjectInputStream class.

import java.io.*;
public class DeserializeExample {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream("student.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        Student s = (Student) in.readObject();
        in.close();
        fileIn.close();
        System.out.println(s.id + " " + s.name);
    }
}

That’s all it takes to implement serialization in Java – a simple interface and two classes from the java.io package. This mechanism is lightweight and efficient for storing object data or transmitting it between applications.

Always ensure that only the required fields are serialized and handle exceptions properly for safe and robust implementations.

Need Help With Integrating Serialization into Your Framework?

Advanced Concepts in Java Serialization

When working with real-world applications, you’ll often need to serialize entire object graphs (nested objects). In such cases, an understanding of Java data structures becomes useful.

You can also gain more control over how your objects behave during serialization using custom methods like writeObject() and readObject(). This level of customization is required in large, modular applications where the facade pattern in Java is commonly used to manage complexity.

serialVersionUID: Version Control for Serialized Objects

serialVersionUID is a unique identifier that verifies the sender and receiver of a serialized object have compatible classes. If you modify a class (like adding a field) without updating the UID, deserialization can fail with an InvalidClassException.

private static final long serialVersionUID = 1L;

Declaring it manually helps maintain backward compatibility between serialized data and class versions.

Skipping Fields with the transient Keyword

If you don’t want certain fields to be serialized (like passwords or temporary data), mark them as transient. These fields will be ignored during serialization and initialized with default values during deserialization.

transient String password; // This won't be serialized

It’s useful when dealing with sensitive or session-based data that doesn’t need persistence.

Serialization of Object Graphs (Nested Objects)

Java handles object graphs – meaning if an object refers to other objects, those references will also be serialized, as long as all objects involved are serializable.

Example:

class Address implements Serializable {
    String city;
}
class Employee implements Serializable {
    Address address; // Will be serialized if Address is also Serializable
}

If a non-serializable object is referenced, serialization will fail with a NotSerializableException.

Custom Serialization Using writeObject() and readObject()

You can override default serialization behavior by defining private methods writeObject() and readObject() in your class. This is useful for encrypting data, skipping sensitive fields, or handling non-serializable components manually.

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();
    // Custom logic (e.g., encrypt a field before writing)
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    // Custom logic (e.g., decrypt or initialize something)
}

These methods give you complete control over the serialization process while still relying on Java’s internal mechanisms.

These advanced techniques allow you to fine-tune how your Java objects are serialized and deserialized. Whether you’re handling sensitive data, managing class versions, or dealing with nested objects, they ensure greater reliability and flexibility in real-world applications.

Full Control and Practical Usage of Java Serialization

If you need complete control over serialization behavior, implement the Externalizable interface. It gives you full command over the read and write process. Serialization is especially important when dealing with Java integration testing, where you may need to store or mock serialized objects to simulate external dependencies.

You can also combine this with popular Java testing frameworks like JUnit or TestNG for effective test coverage.

Full Control with Externalizable

If you need total control over how your object is serialized and deserialized, Java provides the Externalizable interface. Unlike Serializable, this interface requires you to define both writeExternal() and readExternal() methods explicitly.

class Employee implements Externalizable {
    String name;
    int salary;
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
        out.writeInt(salary);
    }
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = in.readUTF();
        salary = in.readInt();
    }
}

This approach is ideal when you want to optimize or filter exactly what data is written and read.

Serialization of Common Java Types

Most standard Java classes like String, ArrayList, HashMap, and wrapper classes (Integer, Double, etc.) are already serializable. You can directly use them in your custom classes and serialize the entire object tree without additional setup, as long as all components implement serializable.

class Data implements Serializable {
    String name;
    ArrayList<Integer> scores;
}

This makes it easy to serialize complex objects containing multiple fields and collections.

File Storage and Network Transfer

Serialization is widely used for storing objects in files and sending them across a network. Saving an object to a .ser file allows it to be restored later. Similarly, serialized objects can be transferred between client and server applications via sockets.

Storing to File:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("object.ser"));
out.writeObject(obj);

Reading from File:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.ser"));
Object obj = in.readObject();

This approach is efficient for persisting temporary data, configuration states, or application sessions. Whether you’re storing objects, sending them over a network, or customizing the serialization process completely, Java provides the tools to handle it effectively.

Using Externalizable, built-in serializable types, and standard I/O streams, you can adapt serialization to meet the exact needs of your application.

Let Our Team Handle Your Java Backend Complexities!

FAQs on Java Serialization

What happens without serialization in Java?

Without serialization, Java objects can’t be saved to a file or sent over a network. You’ll lose the object state once the program ends.

What is @transient in Java?

The transient keyword is used to skip specific fields during Java serialization. Fields marked as transient won’t be saved or restored.

How to avoid serialization in Java?

To avoid serialization in Java, simply don’t implement the Serializable interface in your class. You can also mark sensitive fields as transient.

How to override serialization in Java?

You can override Java serialization by defining custom writeObject() and readObject() methods in your class. This gives you full control over what gets serialized.

What cannot be serialized in Java?

Java can’t serialize objects of classes that don’t implement Serializable. Also, transient fields, static fields, and objects holding OS-level resources (like file handles) are not serialized.

Conclusion

Serialization in Java is a useful way to save object data or send it across networks. It helps keep the object state intact, even after the program ends.

From using the Serializable interface to customizing the process with writeObject() and readObject(), serialization gives developers flexibility and control over object handling.

If you need help implementing serialization or building scalable Java applications, our expert team is here to help. Being a leading Java development agency, we offer custom solutions to meet your business needs. Let’s turn your ideas into high-performance Java apps; get in touch today!

author
Mehul Patel is a seasoned IT Engineer with expertise as a WordPress Developer. With a strong background in Core PHP and WordPress, he has excelled in website development, theme customization, and plugin development.