Serialization

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Serialization is the process of converting an in-memory Java Object into a sequence of bytes.
  • This byte stream can then be saved to a database, written to a file, or sent over a network.
  • The object must implement the marker interface java.io.Serializable.

Concept

An Object in Java lives in the JVM’s Heap memory. It consists of references, memory addresses, and data. If you want to send a User object over an HTTP network to another server, you cannot send raw RAM addresses.
You must flatten the object into a linear stream of bytes. This is Serialization.

Historically, Java provided a built-in mechanism for this using ObjectOutputStream. It takes your object, inspects its fields, and translates them into a proprietary binary format.
Note: In modern development, Java’s built-in binary serialization is rarely used for network communication. Instead, objects are serialized into human-readable text formats like JSON (using Jackson/Gson) or cross-platform binary formats like Protobuf.

Examples

import java.io.*;

// 1. The class MUST implement Serializable
class User implements Serializable {
    private String username;
    
    // The 'transient' keyword prevents this field from being serialized
    private transient String password; 

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    @Override
    public String toString() { return "User{" + username + ", " + password + "}"; }
}

public class SerializationDemo {
    public static void main(String[] args) {
        User user = new User("alice_admin", "superSecret123!");

        // 2. Serialize the object to a file
        try (FileOutputStream fos = new FileOutputStream("user.ser");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
             
            oos.writeObject(user);
            System.out.println("Object serialized successfully!");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Interview Questions

Q: What does the transient keyword do?
A: If a class field is marked as transient, the Java Serialization mechanism will completely ignore it. Its value will not be written to the byte stream. This is crucial for security (e.g., preventing passwords from being saved to disk) or for ignoring non-serializable fields (like an open Socket or Thread reference inside an object). When the object is later deserialized, the transient field will be initialized to its default value (null for objects, 0 for ints).

Q: If class A contains a reference to class B, what happens when you serialize A?
A: The serialization mechanism traverses the entire object graph. If A is serialized, the JVM will automatically serialize the instance of B contained within it. However, class B must also implement Serializable. If B does not implement it, a NotSerializableException will be thrown at runtime and the whole process will fail.