Skip to main content

Java Serialization Example in Java

1 min read Updated May 29, 2026
Share:
On this page (7sections)

Introduction

Serialization converts a Java object into a byte stream for storage or network transfer. Deserialization reconstructs the object from that stream.

Example Program

import java.io.*;

class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private transient String password; // not written to file

    public Student(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    @Override
    public String toString() {
        return "Student{id=" + id + ", name='" + name + "', password='" + password + "'}";
    }
}

public class SerializationDemo {
    public static void main(String[] args) {
        String file = "student.ser";

        Student original = new Student(101, "Thiyagaraaj", "secret123");

        // Serialize
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) {
            out.writeObject(original);
            System.out.println("Serialized: " + original);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialize
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
            Student restored = (Student) in.readObject();
            System.out.println("Deserialized: " + restored);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Sample Output

Serialized: Student{id=101, name='Thiyagaraaj', password='secret123'}
Deserialized: Student{id=101, name='Thiyagaraaj', password='null'}

How It Works

  1. The class implements Serializable (a marker interface).
  2. ObjectOutputStream.writeObject() writes the object graph to a file.
  3. ObjectInputStream.readObject() reads it back.
  4. The transient password field is skipped during serialization, so it becomes null after restore.

Best Practices

  • Declare serialVersionUID for maintainable serializable classes.
  • Mark sensitive fields as transient.
  • Consider JSON or protocol buffers for cross-language persistence instead of Java-native serialization.

Common Mistakes

  • Attempting to serialize a class that does not implement Serializable.
  • Changing class structure without managing version compatibility.

Frequently Asked Questions

What is serialVersionUID?
It is a version identifier for a serializable class. Defining it explicitly helps maintain compatibility when the class structure changes across application versions.
Which fields are not serialized?
Fields marked transient and static fields are not serialized. Objects referenced by non-transient fields must also be serializable unless handled specially.

Related Tutorials

Search tutorials