Skip to content
Veltoryx Technologies
ProLesson 11.3Intermediate3 min readUpdated 30 October 2026

Serialization, and why to avoid it

What Java serialization does, serialVersionUID and transient, why it's a security risk, and the formats to use instead.

Serialization turns an object into bytes, so it can be saved to a file or sent over a network. Deserialization turns the bytes back into an object. Java has a built-in mechanism for this. You need to know it for interviews and old codebases, but modern applications should almost always use something else.

01Built-in Java serialization

A class opts in by implementing the marker interface Serializable:

SerializeDemo.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class UserSession implements Serializable {
    private static final long serialVersionUID = 1L;   // version of the class's format

    final String username;
    final int loginCount;
    transient String password;                         // transient: NOT serialized

    UserSession(String username, int loginCount, String password) {
        this.username = username;
        this.loginCount = loginCount;
        this.password = password;
    }
}

public class SerializeDemo {
    public static void main(String[] args) throws Exception {
        UserSession original = new UserSession("asha", 7, "s3cret");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(original);                 // object → bytes
        }

        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            UserSession copy = (UserSession) in.readObject();   // bytes → object
            System.out.println(copy.username + ", logins " + copy.loginCount);
            System.out.println("password after deserialization: " + copy.password);
        }
    }
}
Expected output
asha, logins 7
password after deserialization: null

Loading the rest of the lesson…