How do you serialize and deserialize an object in Java?
Table of Contents
Introduction
Serialization in Java is the process of converting an object into a byte stream, enabling it to be easily saved to a file or transmitted over a network. Deserialization is the reverse process, where the byte stream is converted back into a Java object. This guide provides a clear example of how to serialize and deserialize an object in Java.
1. Create a Serializable Class
To serialize an object, the class must implement the Serializable
interface. This allows Java to know that the object can be converted to a byte stream.
Example Class:
2. Serialize the Object
To serialize an object, you can use ObjectOutputStream
, which writes the object to a file or an output stream.
Serialization Example:
3. Deserialize the Object
To deserialize an object, use ObjectInputStream
, which reads the byte stream and reconstructs the object.
Deserialization Example:
4. Complete Example
Combining the serialization and deserialization processes, here’s the complete example in one place.
Complete Code:
Conclusion
Serialization and deserialization in Java are essential for object persistence and data transfer. By implementing the Serializable
interface and using ObjectOutputStream
and ObjectInputStream
, you can easily convert objects to and from byte streams. This process is fundamental in applications that require data storage, remote communication, and session management, making it an essential skill for Java developers.