Java Serialization and Deserialization – Complete Guide with Examples
Learn how to serialize Java objects into byte streams and deserialize them back, including implementation, transient fields, and versioning for efficient object storage and transfer.
Serialization and Deserialization in Java – Complete Detailed Tutorial
Serialization in Java allows you to convert objects into a byte stream for storage or transmission.
Deserialization is the reverse process – converting the byte stream back into a Java object.
These concepts are part of java.io package.
1. Why Serialization is Used
- Persist objects to files or databases
- Send objects over networks (RMI, sockets)
- Store objects in cache
- Clone objects or maintain object state
2. Serializable Interface
- Marker interface (no methods)
- Classes implementing
Serializablecan be serialized
Key Points:
- Implements java.io.Serializable
- No methods to override
- All fields are serialized by default
3. Serializing Objects
- Use ObjectOutputStream with FileOutputStream
Explanation:
- Object is converted into a byte stream
- Saved in student.ser file
4. Deserializing Objects
- Use ObjectInputStream with FileInputStream
Output:
5. Transient Fields
- Fields declared as
transientare not serialized
- During deserialization,
agewill be default value (0)
6. serialVersionUID
- Unique identifier for class versioning
- Helps maintain compatibility during deserialization
- If class structure changes, it prevents InvalidClassException
7. Key Points
- Serialization converts object → byte stream
- Deserialization converts byte stream → object
- Use transient for non-serializable fields
- Always define serialVersionUID for version control
- Implements Serializable interface (marker interface)
8. Summary
- Java provides ObjectOutputStream and ObjectInputStream
- Essential for persistent storage and network communication
- Works with custom objects safely
- Core concept for Java I/O Streams