Java Serialization Example in Java
On this page (7sections)
Introduction
Serialization converts a Java object into a byte stream for storage or network transfer. Deserialization reconstructs the object from that stream.
Example Program
import java.io.*;
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private transient String password; // not written to file
public Student(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "', password='" + password + "'}";
}
}
public class SerializationDemo {
public static void main(String[] args) {
String file = "student.ser";
Student original = new Student(101, "Thiyagaraaj", "secret123");
// Serialize
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file))) {
out.writeObject(original);
System.out.println("Serialized: " + original);
} catch (IOException e) {
e.printStackTrace();
}
// Deserialize
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
Student restored = (Student) in.readObject();
System.out.println("Deserialized: " + restored);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Sample Output
Serialized: Student{id=101, name='Thiyagaraaj', password='secret123'}
Deserialized: Student{id=101, name='Thiyagaraaj', password='null'}
How It Works
- The class implements
Serializable(a marker interface). ObjectOutputStream.writeObject()writes the object graph to a file.ObjectInputStream.readObject()reads it back.- The
transientpassword field is skipped during serialization, so it becomesnullafter restore.
Best Practices
- Declare
serialVersionUIDfor maintainable serializable classes. - Mark sensitive fields as
transient. - Consider JSON or protocol buffers for cross-language persistence instead of Java-native serialization.
Common Mistakes
- Attempting to serialize a class that does not implement
Serializable. - Changing class structure without managing version compatibility.
Frequently Asked Questions
What is serialVersionUID?
It is a version identifier for a serializable class. Defining it explicitly helps maintain compatibility when the class structure changes across application versions.
Which fields are not serialized?
Fields marked transient and static fields are not serialized. Objects referenced by non-transient fields must also be serializable unless handled specially.