Letβs say youβre in a Java interview and the topic of object persistence comes up. Hereβs how an interactive interview-style conversation about Serialization vs Externalization might go:
π¨βπΌ Interviewer: Can you explain what Serialization is in Java?
π¨βπ» You: Sure! Serialization is the process of converting a Java object into a byte stream, so it can be saved to a file or sent over the network. We can later recreate the object using deserialization.
π¨βπΌ Interviewer: And how do you make a class Serializable?
π¨βπ» You: We just need to implement the java.io.Serializable interface. Itβs a marker interface β it doesnβt have any methods.
public class Employee implements Serializable {
private int id;
private String name;
}
π¨βπΌ Interviewer: What is Externalization, and how is it different?
π¨βπ» You: Externalization gives us more control over what gets serialized and how. We implement the Externalizableinterface, which has two methods:
- writeExternal(ObjectOutput out)
- readExternal(ObjectInput in)
Unlike Serialization, here we write the logic manually.
public class Employee implements Externalizable {
private int id;
private String name;
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id);
out.writeObject(name);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
id = in.readInt();
name = (String) in.readObject();
}
}
π¨βπΌ Interviewer: So whatβs the main difference between the two?
π¨βπ» You: Hereβs a quick comparison:
Feature | Serialization | Externalization |
---|---|---|
Interface | Serializable | Externalizable |
Control | Automatic | Manual (custom logic) |
Performance | Slower (writes all fields) | Faster (you choose what to write) |
Default constructor needed? | No | Yes, it must have a public no-arg constructor |
Versioning | Supports serialVersionUID | Also supports it, but you manage the structure manually |
π¨βπΌ Interviewer: When would you use Externalization over Serialization?
π¨βπ» You: If I want to control exactly which fields to save (maybe skip passwords or cache fields), Externalization is better. It also performs better if we have large objects with unnecessary fields.
π¨βπΌ Interviewer: Are there any risks or gotchas?
π¨βπ» You: Yes. With Externalization:
- We must be careful with the read/write order.
- It needs a public no-argument constructor.
- If we miss writing or reading a field, data loss or exceptions can happen.
π¨βπΌ Interviewer: Can we use transient keyword with both?
π¨βπ» You: Yes, but itβs more useful in Serializable. With Externalizable, since we control the logic, we just skip writing that field.
Final Tip:
Use Serialization if default behavior is fine. Choose Externalization if you care about performance or need full control over the process.
Want a quick demo project for both? Just let me know!
Leave a Reply