Serialization, Deserialization and Externalization in Java
In Java interviews, one of the most common topics you’ll encounter is object persistence—how Java objects are saved, transferred, and reconstructed. This is where concepts like Serialization, Deserialization, and Externalization come into play.
These aren’t just theoretical ideas; they are crucial in distributed systems, caching, session management, and inter-process communication. Let’s explore these concepts step by step, highlight their differences, and discuss real-world use cases.
1. What is Serialization in Java?
Serialization is the process of converting a Java object into a byte stream so that it can be stored in a file, transmitted over a network, or persisted in a database.
How it works:
- The class must implement the
Serializableinterface (marker interface). - Use
ObjectOutputStream.writeObject()to serialize an object. - Non-transient, non-static fields are serialized; transient fields are skipped.
serialVersionUIDensures version compatibility.
Example: Serialization
import java.io.*;
class Student implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String name;
transient String password; // will not be serialized
Student(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
}
public class SerializeDemo {
public static void main(String[] args) {
try {
Student s1 = new Student(101, "Naveen", "secret123");
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(s1);
out.close();
fileOut.close();
System.out.println("Object serialized and saved in student.ser");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. What is Deserialization in Java?
Deserialization is the reverse process—converting a byte stream back into a Java object.
Key Points:
- The class definition must be present on the JVM.
- Constructors are not invoked during deserialization.
- Transient fields are restored to default values (
null,0,false).
Example: Deserialization
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Student s1 = (Student) in.readObject();
in.close();
fileIn.close();
System.out.println("ID: " + s1.id);
System.out.println("Name: " + s1.name);
System.out.println("Password: " + s1.password); // will be null
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
ID: 101 Name: Naveen Password: null
3. What is Externalization in Java?
Externalization provides full control over serialization. Instead of relying on Java’s default mechanism,
you manually define how objects are written and read using the Externalizable interface.
How it works:
- Implement the
Externalizableinterface. - Override
writeExternal()andreadExternal(). - A public no-arg constructor is mandatory.
Example: Externalization
import java.io.*;
class Employee implements Externalizable {
int id;
String name;
String role;
public Employee() {} // required no-arg constructor
Employee(int id, String name, String role) {
this.id = id;
this.name = name;
this.role = role;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id);
out.writeObject(name);
// skipping role field intentionally
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
id = in.readInt();
name = (String) in.readObject();
// role will remain null
}
}
public class ExternalizationDemo {
public static void main(String[] args) throws Exception {
Employee emp = new Employee(201, "John", "Developer");
// Serialize
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"));
emp.writeExternal(oos);
oos.close();
// Deserialize
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"));
Employee emp2 = new Employee();
emp2.readExternal(ois);
ois.close();
System.out.println(emp2.id + " " + emp2.name + " " + emp2.role);
}
}
4. Serialization vs Externalization
| Feature | Serialization (Serializable) | Externalization (Externalizable) |
|---|---|---|
| Control | Automatic (default Java mechanism) | Manual (developer-defined) |
| Performance | Slower (writes all non-transient fields) | Faster (you decide what to write) |
| Flexibility | Limited | High – custom logic possible |
| Versioning | Can break if class changes | Easier to manage changes |
| Constructor Call | No constructor called | Calls public no-arg constructor |
5. Real-World Use Cases
- Serialization: Session persistence, caching, sending objects over a network (RMI).
- Deserialization: Receiving objects from remote servers, restoring cached objects.
- Externalization: Performance optimization, skipping sensitive fields, ensuring backward compatibility.
6. Common Interview Questions
- Q: What is the difference between Serializable and Externalizable?
A: Serializable is automatic, Externalizable is manual and gives full control. - Q: What happens to transient and static variables?
A: They are not serialized. - Q: Why use serialVersionUID?
A: To maintain compatibility between class versions. - Q: Are constructors called during deserialization?
A: Not for Serializable, but yes for Externalizable.
Conclusion
Serialization, deserialization, and externalization form the backbone of Java object persistence. Use Serialization for simplicity, Deserialization to reconstruct objects, and Externalization when you need fine-grained control. Mastering these concepts will not only make you a stronger Java developer but also help you ace interview questions with confidence.
Comments
Post a Comment