Serialization in Java
Serialization converts a Java object's state into a byte stream that can be saved to a file, sent over a network, or stored anywhere bytes can go; deserialization reverses that process, reconstructing an equivalent object from a previously-serialized byte stream. A class opts into this by implementing the Serializable interface, a marker interface that declares no methods at all — it just signals to the JVM that objects of this class are allowed to be serialized.
Every field in a serializable class gets included in the byte stream by default unless it's marked transient, which explicitly excludes that one field — useful for data that shouldn't be persisted, like a cached value, or genuinely can't be, like a database connection. A serialVersionUID field, though technically optional, is strongly recommended, since it lets the JVM verify a deserialized byte stream's class version still matches the current class definition, rather than failing unpredictably if the class has changed since that object was originally serialized.
Writing the object out
Converts an object's state into a byte stream that can be saved or transmitted.
Deserialization
Reverses the process, reconstructing an equivalent object from that byte stream.
The Serializable interface
A marker interface with no methods at all, just an opt-in signal that a class's objects are allowed to be serialized.
transient fields
Explicitly excluded from the byte stream, for data that shouldn't be persisted or genuinely can't be, like a live connection.
serialVersionUID
A recommended field that lets the JVM verify a deserialized stream's class version still matches the current class definition.
import java.io.*; public class SerializationDemo { static class User implements Serializable { String name; transient String sessionToken; User(String name, String sessionToken) { this.name = name; this.sessionToken = sessionToken; } } public static void main(String[] args) throws Exception { User original = new User("Ana", "secret-token"); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); new ObjectOutputStream(byteStream).writeObject(original); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(byteStream.toByteArray())); User restored = (User) in.readObject(); System.out.println("Name: " + restored.name); System.out.println("Token: " + restored.sessionToken); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.