Java Notes
Complete guide to Serialization in Java — converting objects to byte streams, Serializable interface, ObjectOutputStream, transient keyword, serialVersionUID, and custom serialization.
What is Serialization?
Serialization is the process of converting a Java object's state into a byte stream, so it can be:
- Saved to a file (persistence)
- Sent over a network (remote communication)
- Stored in a database (as BLOB)
- Cached in memory systems (Redis, Memcached)
Serialization
Java Object →→→ Byte Stream →→→ File/Network/Database
(in memory) (portable) (persistent storage)
Deserialization (reverse)
File/Network →→→ Byte Stream →→→ Java Object
(storage) (portable) (back in memory)
The Serializable Interface
To make a class serializable, implement java.io.Serializable:
import java.io.Serializable;
// Serializable is a MARKER interface (no methods to implement)
public class Student implements Serializable {
private String name;
private int age;
private double gpa;
public Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}
@Override
public String toString() {
return String.format("Student{name='%s', age=%d, gpa=%.2f}", name, age, gpa);
}
}Basic Serialization with ObjectOutputStream
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
The transient Keyword
Fields marked transient are excluded from serialization:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| Before serialization | UserAccount{user='alice', pass='secret123', email='alice@mail.com', role='admin', attempts=0} |
| After deserialization | UserAccount{user='alice', pass='null', email='alice@mail.com', role='admin', attempts=0} |
| Notice | password is null, loginAttempts is 0 |
| - Objects | null |
| - int | 0 |
| - boolean | false |
| - double | 0.0 |
serialVersionUID
The serialVersionUID is a version identifier for the serialized class. It ensures compatibility between the serializer and deserializer:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Serializing Multiple Objects
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
Serialization with Inheritance
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
Custom Serialization (writeObject / readObject)
You can control exactly what gets serialized:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Output:
| Original | Config{url='https://api.example.com', apiKey='sk-secret-key-123', timeout=30000} |
| [Custom writeObject | apiKey encrypted] |
| [Custom readObject | apiKey decrypted] |
| Restored | Config{url='https://api.example.com', apiKey='sk-secret-key-123', timeout=30000} |
Common Mistakes
1. Forgetting to implement Serializable
// ❌ NotSerializableException at runtime!
class MyClass {
// missing: implements Serializable
}
// ✅ Always implement Serializable
class MyClass implements Serializable { }2. Non-serializable fields
// ❌ If a field's class isn't Serializable, the whole object fails
class DataHolder implements Serializable {
private Socket connection; // Socket isn't Serializable → Exception!
}
// ✅ Mark non-serializable fields as transient
class DataHolder implements Serializable {
private transient Socket connection; // Excluded from serialization
}3. Not declaring serialVersionUID
// ❌ JVM generates one automatically — breaks if class changes
class MyClass implements Serializable { }
// ✅ Always declare explicitly
class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
}Interview Questions
Q1: What is serialization in Java?
Answer: Serialization is the process of converting a Java object into a byte stream so it can be persisted to a file, sent over a network, or stored in a database. The reverse process (byte stream → object) is deserialization.
Q2: What is the Serializable interface? Why is it called a marker interface?
Answer: Serializable is an interface with NO methods. It's called a "marker" interface because it simply marks/tags a class as eligible for serialization. The JVM checks for this marker before allowing serialization.
Q3: What is the transient keyword?
Answer: transient marks a field to be excluded from serialization. During deserialization, transient fields receive their default values (null for objects, 0 for numbers, false for booleans). Use it for sensitive data (passwords), derived values, or non-serializable fields (connections, threads).
Q4: What is serialVersionUID and why is it important?
Answer: It's a version number for the serialized class. During deserialization, JVM compares the sender's UID with the receiver's. If they don't match, it throws InvalidClassException. Declaring it explicitly allows controlled class evolution (adding fields without breaking existing serialized data).
Q5: What happens if a parent class is not Serializable but the child is?
Answer: Only the child's fields are serialized. During deserialization, the parent's no-argument constructor is called to initialize parent fields. If the parent doesn't have a no-arg constructor, deserialization fails with InvalidClassException.
Q6: Can static fields be serialized?
Answer: No. Static fields belong to the class, not to any instance. Serialization saves instance state only. However, serialVersionUID (which is static) is a special case used by the serialization mechanism itself.
Continue the lesson path