InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
What is the difference between Serialization or Serializable and Externalization or Externalizable?
Serialization (Serializable):
1: Serialization is the process of converting an object into a byte stream so it can be saved to a file or sent over a network.
2: If a class implements Serializable, Java automatically handles the serialization of all its fields.
3: You don’t need to write any extra code, just implement the interface.
Example:
class Student implements Serializable {
int id;
String name;
}
Here, all fields (id, name) will be serialized automatically.
Externalization (Externalizable):
1: Externalization is also used to convert an object into a byte stream, but gives you full control over what and how to serialize.
2: You must implement the writeExternal() and readExternal() methods to manually specify which fields to serialize and how.
3: Useful when you want to exclude some fields or customize the process.
Example:
class Student implements Externalizable {
int id;
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();
}
}
Here, you decide which fields to save and how.
Easy Way to Remember:
1: Serializable - Java does everything for you, just implement the interface.
2: Externalizable - You do everything yourself, write the methods to control serialization.
Summary Table:
Feature Serializable Externalizable
Control Automatic Manual
Methods
Required None writeExternal/readExternal
Usage Simple objects Custom serialization
In Short:
Serializable = automatic, easy
Externalizable = manual, flexible