Serializable

The Serializable interface in Java is a marker interface (i.e., it has no methods) that allows an object to be converted into a byte stream, which can then be saved to a file or sent over a network. It enables object persistence and object transfer.

To make a class serializable, it must:

  • Implement java.io.Serializable.
  • Ensure all non-transient fields are also serializable.

Simple Program: Serialize and Deserialize an Object

LotusJavaPrince wants to save Mahesh’s user profile data into a file and restore it later.

import java.io.*;

// Step 1: Make the class serializable
class UserProfile implements Serializable {
    String name;
    int age;
    transient String password; // Won't be saved

    public UserProfile(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
}

public class SimpleSerialization {
    public static void main(String[] args) {
        UserProfile user = new UserProfile("Mahesh", 30, "secret123");

        // Serialization
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
            oos.writeObject(user);
            System.out.println("Object serialized.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"))) {
            UserProfile deserializedUser = (UserProfile) ois.readObject();
            System.out.println("Name: " + deserializedUser.name);
            System.out.println("Age: " + deserializedUser.age);
            System.out.println("Password: " + deserializedUser.password); // null (transient)
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output

Object serialized.
Name: Mahesh
Age: 30
Password: nullCode language: JavaScript (javascript)

The Serializable interface enables Java objects to be saved and restored across JVM sessions or sent across systems — making it a cornerstone of persistence, networking, and distributed applications. With proper care, Serializable empowers systems like file backups, RMI, session storage, and object cloning.

Scroll to Top