Serialization and Deserialization
Serialization is a process of converting the state of an object into a byte stream. Deserialization is the reverse mechanism of serialization where the task of byte stream is to reconstruct the real object of Java in memory. This method is used to persist the object.
The serialized classes should have the implementation of a java.io.Serializable interface. Serializable Interface in Java is used to mark classes, it is mainly marker interface.
Before we go deeper into it, let’s originally be aware of what are streams in computer systems. A stream is nothing but the chain of data elements. In our computer system, there is a source that generates information in the form of a stream and there is a destination which reads and consumes this stream. Types of streams are given as below:
Byte stream uses 8-bit to store a single character. Java program is used to perform byte stream operation. The byte stream is a low-level input-output operation.
This stream is composed of characters (stream) with an accurate encoding scheme such as UNICODE, ASCII etc. Dissimilar byte stream, the character stream will automatically translate to and from the local character set. JAVA language uses UNICODE system to store characters as a character stream.
When we convert the state of a JAVA object into a byte stream that can be stored into a file, database, or transported to any known location like from web tier to app tier as data value object in client-server RMI applications. This procedure of writing the object state into a byte stream is known as Serialization.
To perform binary IO operations for all the primitive data types in Java data stream is used. Through data stream we can execute I/O operations in a well-organized and suitable way for int, char, byte, short, long, float, double, Boolean, and Strings, etc. by using data stream.
Finally, we can use this byte stream to recover the stored values and return the object’s previous state. This procedure of restoring the object’s old state is known as Deserialization.
Here are following important points to be noted –
1) Associated objects must be implementing the Serializable interface.
2) If a superclass has implemented a Serializable interface then subclass doesn’t need to implement it but vice-versa is not true.
3) Only non-static data members are saved via Serialization process.
4) A constructor of an object is never called when an object is deserialized.
5) Static data members and transient data members are not saved via Serialization process.
Example of Serialization:
Hope this blog helps you understand the concept of serialization and deserialization better. Let us know if you have any feedback in the comment section below.
For more such content subscribe to our YouTube channel – https://www.youtube.com/channel/UCcWR1IezEQynJnAETgK8g2w?sub_confirmation=1