Clean • Professional
Serialization and Deserialization are mechanisms in Java that allow objects to be converted to bytes and restored back to objects. They are mainly used for saving object data, transferring objects over networks, caching, and deep cloning.
Serialization is the process of converting a Java object into a byte stream.
This byte stream can then be:
Serialization allows the object’s state to be preserved.
Basic Example of Serialization
import java.io.*;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class SerializeExample {
public static void main(String[] args) {
Student s = new Student(101, "Durgesh");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
oos.writeObject(s);
System.out.println("Object serialized successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
To serialize an object, the class must implement:
class Student implements Serializable { }
Deserialization is the reverse process — converting a byte stream back into an actual Java object.
This restores the object into memory with the same values that it had when serialized.
Deserialization Example
import java.io.*;
public class DeserializeExample {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student s = (Student) ois.readObject();
System.out.println("ID: " + s.id);
System.out.println("Name: " + s.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
A) Fields marked transient are NOT serialized
Used for sensitive or temporary data.
transient String password;
B) Static fields are NOT serialized
Because they belong to the class, not the object.
C) Class should have a serialVersionUID
To avoid version mismatch errors.
Used to verify that a serialized object matches the class definition.
private static final long serialVersionUID = 1L;
If missing, JVM auto-generates it (not recommended).
You can customize how objects are serialized:
private void writeObject(ObjectOutputStream oos) throws Exception {
oos.defaultWriteObject();
}
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
}
Serializabletransient)1. Save Application State
Example: Game progress, UI state, form data.
2. Transfer Objects Over Network
Used in:
3. Store Objects in Files or Databases
Storing user profiles, logs, sessions.
4. Caching Objects
Frameworks like Ehcache store serialized objects.
5. Deep Cloning of Objects
Serialize → Deserialize → Get new copy.