What is meant by Serialization? , Why we need Serialization ? , How to do serialization ? These are the questions come to our mind when we talk about serialization. From this post I am going to answer for above questions one by one.
Serialization is the process of converting an object to a byte stream. Deserialization is the process of reconstructing an object that has been serialized before.
Let's look at why we need to do serialization. Java objects are created on the memory area called a Heap.This is a temporary memory location. Which means when we terminate our application heap memory is cleaned. So all the objects which were on the heap memory are lost. So, if we need to save those objects for future use Serialization is the way to go. And also when we want to transfer objects through a network we can use serialization.
Below code segment demonstrate how to do serialization in java. Here I have created two java classes .First one is Participant class. It is the one I am going to serialize. My second class is called TestSerialization . In that class I have serialized an Arraylist of Participant objects into a file.
Now let's look at how to do deserialization. For testing deserialization I am going to create a new class called TestDeserialization. Here what I am going to do is deserialize participant objects in the "participantlist.ser" file.
Above class will print below result in the console as the output.
[firstName = hasitha lastName = thamaranga Age = 25, firstName = sansala lastName = dilshan Age = 22, firstName = kasun lastName = amarasena Age = 26, firstName = akila lastName = sathsara Age = 28, firstName = gayan lastName = kumara Age = 30]