Object serialization in Java converts an object's state into a byte stream suitable for storage or transmission. Deserialization reconstructs the object from that byte stream. This capability is enabled by implementing the java.io.Serializable interface.
Implementing Serializable
A class must implement Serializable—a marker interface with no methods—to support serialization:
import java.io.Serializable;
public class DataRecord implements Serializable {
private static final long serialVersionUID = 42L;
// fields and methods
}
Serializing an Object
Use ObjectOutputStream to write an object to a file or stream:
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) {
DataRecord record = new DataRecord();
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"))) {
out.writeObject(record);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Deserializing an Object
Reconstruct the object using ObjectInputStream:
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeDemo {
public static void main(String[] args) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.ser"))) {
DataRecord record = (DataRecord) in.readObject();
// use the restored object
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Special Considerations
- Non-serializable references: If a serializable object holds a refeernce to a non-serializable object, serialization fails with
NotSerializableException. - Version control: The
serialVersionUIDfield ensures compatibility between serialized data and class versions. Omitting it may cause version mismatch issues. - Custom logic: Define
private void writeObject(java.io.ObjectOutputStream)andprivate void readObject(java.io.ObjectInputStream)to override default serialization behavior.
Key Points
- Only instances of classes implementing
Serializablecan be serialized. - Static and transient fields are excluded from serialization.
- Serialization captures runtime state, not code or method definitions.
- I/O exceptions must be handled during serialization operations.