Object Serialization – Saving Objects in Java

Serialization is the process of converting the state of an object into byte stream.After the object is serialized has been written into a file, it can be read from the file and deserialized that is bytes that represent the object and its data can be used to recreate the objects in memory.

Writing Serialized Object to a file

Step-1
Implement Serializable interface in your class. Serializable interface is known as a marker interface because the interface doesn’t have any methods to implement.Its only purpose is to announce that the class implementing it is serializable.If any superclass of a class is serializable the subclass is automatically serializable even if the subclass doesn’t explicitly implement serializable.

Step-2
Make FileOutputStream and ObjectOutputStream

FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);

ObjectOutputStream os =  new ObjectOutputStream(fileStream);

Step -3
Write the object

os.writeObject(obj1);

os.writeObject(obj2);

Step-4

Close the stream

os.close();

Serialized objects save the values of the object’s instance variables, so that an identical instance object can be brought back to life when object is deserialized.

When an object is serialized the entire object graph is saved to the file that is all the instance variables, all the objects those objects refer to and all the objects those objects refer to and so on .And all of it happens automatically.

Transient Variables and Serialization

If you want an instance variable to be skipped during serialization, mark them transient.During deserialization the transient variable are set to their initial values 

Reading Serialized Object from a file

Deserialization is like serialization process in reverse, restoring an object to life in the same state in which it was saved to file ,except for the transient variables which comes back either null or as default primitive values.

Step-1

Make FileInputStream and ObjectInputStream
FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);

ObjectOutputStream os = new ObjectOutputStream(fileStream

Step-2

Read the Objects
Object one = os.readObject();

Object two = os.readObject();

Step-3

Cast the objects to their type

Step-4

Close the ObjectInputStream

os.close();
Please note that the static variables are not serialized.Static variables are not saved and when an object is deserialized it will have static variable its class currently has 

Serialization Example

Serialization Example

Writing Objects to a file

Reading Objects from a file

Deserialization Example

Executing the serializable example

Please note that the default location of Person.ser file will be under the src folder

References:- Oracle Docs

I hope you guys enjoyed reading this article.Happy Coding everyone 🙂

Leave a comment

Your email address will not be published. Required fields are marked *