Sure! Let’s go step by step and cover serialization and deserialization in Java in a clear way.
1. What is Serialization?
Serialization is the process of converting a Java object into a byte stream, so it can be:
- Saved to a file
- Sent over a network
- Stored in a database
This allows the object’s state to be preserved and restored later.
Key Points:
- Only the state of the object (its fields) is saved, not the behavior (methods).
- The class must implement the
Serializable
interface.
2. What is Deserialization?
Deserialization is the reverse process of serialization:
- Converting a byte stream back into a Java object.
- The object can then be used as a normal Java object again.
3. How to Serialize an Object
- Make the class implement
java.io.Serializable
. - Use
ObjectOutputStream
to write the object to a file.
Example:
import java.io.*;
class Student implements Serializable {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}
public class SerializeDemo {
public static void main(String[] args) {
Student s1 = new Student("Alice", 20);
try {
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(s1); // Serialize the object
out.close();
fileOut.close();
System.out.println("Serialization done.");
} catch (IOException i) {
i.printStackTrace();
}
}
}
4. How to Deserialize an Object
Use ObjectInputStream
to read the object back.
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
Student s = null;
try {
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
s = (Student) in.readObject(); // Deserialize
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Student class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Student: " + s);
}
}
5. Important Notes
Serializable
Interface:
It’s a marker interface (no methods) used to indicate the class can be serialized.transient
Keyword:
Fields marked astransient
are not serialized.private transient int ssn;
serialVersionUID
:
It’s a unique ID to ensure the class is compatible during deserialization.private static final long serialVersionUID = 1L;
- Exceptions:
NotSerializableException
→ if class doesn’t implementSerializable
.IOException
andClassNotFoundException
are common during serialization/deserialization.
✅ Summary Table
Concept | Purpose |
---|---|
Serialization | Convert object → byte stream |
Deserialization | Convert byte stream → object |
Serializable | Marker interface for serializable classes |
transient | Skip fields during serialization |
serialVersionUID | Version control for serialized objects |