Friday, June 9, 2023
HomeJavaJava Serialization Instance - Find out how to Serialize and Deserialize Objects...

Java Serialization Instance – Find out how to Serialize and Deserialize Objects in Java?Tutorial

Serialization is without doubt one of the necessary however complicated ideas in Java. Even skilled Java builders wrestle to implement Serialization appropriately. The Serialisation mechanism is offered by Java to save lots of and restore the state of an object programmatically. Java gives two lessons Serializable and Externalizable in bundle to facilitate this course of, each are marker interfaces i.e. an interface with none strategies. Serializing an Object in Java means changing it right into a wire format to be able to both persist its state in a file regionally or switch it to a different consumer through the community, therefore it turns into an especially necessary idea in distributed functions operating throughout a number of JVMs.

There are different options in Java like Distant Methodology Invocation (RMI) or HttpSession in Servlet API which mandates the collaborating object ought to implement a 
Serializable interface as a result of they could be transferred and saved throughout the community.

On this article, I’ve tried to elucidate the idea and means of Serialization by taking a easy instance of a general-purpose object in Java. We’ve a category known as Shoe, which represents a Shoe, which has an occasion variable to symbolize id, shade, and dimension, and a static variable to symbolize a model. I’ve included each transient and static variables to show that these fields will not be saved throughout the Serialization course of.

It’s also possible to learn Head First Java to study extra concerning the delicate particulars of Serialization in Java. They’ve lined the serialization subject excellent, with neither an excessive amount of element nor trivial clarification. I’ve realized a variety of helpful particulars from there.

I’ve additionally defined the reverse means of Serialization to revive the state of the article i.e. de-serialization and why SerialVersionUID is necessary for any serializable class. As soon as we restore the article we print its state to match values earlier than serialization. This will provide you with a transparent concept of how one can save and restore objects in Java.

And, In case you are new to the Java world then I additionally suggest you undergo The Full Java MasterClass on Udemy to study Java in a greater and extra structured approach. This is without doubt one of the finest and up-to-date programs to study Java on-line.

Java Program to Serialize an Object utilizing Serializable interface

Right here is our Java program to exhibit learn how to serialize and de-serialize an object in Java. This program incorporates two lessons Shoe and SerializationDemo, the primary class is our POJO, we’ll create an object of this class and serialize it. 

The second class is our software class which incorporates the predominant() methodology, all of the code to create an object, saving it, and eventually restoring it written inside the principle methodology.

import java.util.logging.Logger;

 * Easy instance of Serialization in Java. We first create a Shoe object, then
 * serializes it and eventually restored it through the use of de-serialization.
 * @creator Javin Paul
public class Sample {

    public static void predominant(String args[]) throws IOException, 
                               ClassNotFoundException {
        Shoe whiteNikeShoe = new Shoe("Nike", 1000, 9, "WHITE", true);
        System.out.println("Earlier than Serialization");

        // serializing shoe object

        // creating one other Shoe with completely different model
        Shoe blackAdidasShoe = new Shoe("Adidas", 2000, 8, "Black", true);
        // deserializing shoe object
        whiteNikeShoe = (Shoe) readShoe();

        System.out.println("After DeSerialization");

    non-public static void writeShoe(Serializable shoe) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(
                        new FileOutputStream(new File("shoe.ser")));

    non-public static Object readShoe() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(
                        new FileInputStream(new File("shoe.ser")));
        Object obj = ois.readObject();
        return obj;


class Shoe implements Serializable {

    // static ultimate variable
    non-public static ultimate lengthy serialVersionUID = 40L;
    non-public static ultimate Logger logger = Logger.getLogger(Shoe.class.getName());

    // static variable however not ultimate
    non-public static String _brand;

    // occasion variable
    non-public int _id;
    non-public int _size;
    non-public String _color;

    // transient variable
    non-public transient boolean _isRunningShoe;

    // non serializable discipline
    Thread _thread;

    public Shoe(String model, int id, int dimension, String shade, 
                                      boolean isRunningShoe) {
        System.out.println("Inside Constructor");
        _brand = model;
        _id = id;
        _size = dimension;
        _color = shade;
        _isRunningShoe = isRunningShoe;


    public String model() {
        return _brand;

    public int id() {
        return _id;

    public int dimension() {
        return _size;

    public String shade() {
        return _color;

    public void print() {
        System.out.println("SerialVersionUID (ultimate static discipline) : "
                            + serialVersionUID);
        System.out.println("logger ((ultimate static discipline) : " + logger);
        System.out.println("_brand (static discipline) : " + _brand);
        System.out.println("_id (occasion variable) : " + _id);
        System.out.println("_size (occasion variable) : " + _size);
        System.out.println("_color (occasion variable) : " + _color);
        System.out.println("_isRunningShoed (transient variable) : " 
                              + _isRunningShoe);
        System.out.println("_thread (non-serializable discipline) : " + _thread);



Inside Constructor
Earlier than Serialization
SerialVersionUID (ultimate static discipline) : 40
logger ((ultimate static discipline) : java.util.logging.Logger@42aab87f
_brand (static discipline) : Nike
_id (occasion variable) : 1000
_size (occasion variable) : 9
_color (occasion variable) : WHITE
_isRunningShoed (transient variable) : true
_thread (non-serializable discipline) : null
Inside Constructor
After DeSerialization
SerialVersionUID (ultimate static discipline) : 40
logger ((ultimate static discipline) : java.util.logging.Logger@42aab87f
_brand (static discipline) : Adidas
_id (occasion variable) : 1000
_size (occasion variable) : 9
_color (occasion variable) : WHITE
_isRunningShoed (transient variable) : false
_thread (non-serializable discipline) : null

An image is value a thousand phrases, so here’s a diagram that explains the serialization and deserialization course of from a 10K ft view:

How to Serialize Object in Java - Serialization Example

Statement and Clarification

Now let’s attempt to perceive what occurred once we serialize an occasion of Shoe and later once we de-serialized it. I’ve created several types of variables on this class to point out that whether or not their worth is persevered or restored throughout Serialization or not. 

Within the Shoe class, now we have two static ultimate fields, SerialVersionUID, and Logger; their values will not be persevered however as a result of they’re static. They’re additionally initialized on the time of sophistication loading, so they’re effective. Additionally, as a result of they’re ultimate, there isn’t any hazard of somebody altering their worth.

The SerialVersionUID is a vital discipline for a serializable class and you must at all times outline it. In the event you do not outline then JVM will calculate this worth by studying the construction of the category e.g. variety of occasion variables, their varieties, and many others. 

This implies subsequent time you add one other occasion variable otherwise you take away the previous one, you danger getting a special SerialVersionUID and if that occurs you will not be capable of restore the article saved by the earlier model of your program.

This has truly occurred to us when one of many builders by chance eliminated the SerialVersionUID from one of many person preferences lessons and when the person downloads and run the brand new model of our Java software, his preferences had been all gone. 

He was a dealer and for them, their preferences imply so much, it was a tough time to console and pacify him earlier than we reverted again his GUI to the earlier model and restored his preferences. I’m positive, you’ll by no means need to upset your purchasers and person.

Serialization is stuffed with such particulars and I extremely suggest studying Joshua Bloch’s recommendation on Efficient Java associated to Serialization earlier than implementing it in your real-world venture. These are invaluable items of recommendation and key to efficiently and appropriately implement Serliazable in something apart from a demo program like this one.

Serialization best practices in Java

Now let’s come to a easy, non-final static variable, its worth can also be not persevered throughout Serialization, that is why you see _brand=Nike earlier than Serialization and _brand=Adidas after. 

Are you aware why it occurred? as a result of once we created one other occasion of Shoe for Adidas, we reset the worth of this variable to “Adidas”, and for the reason that constructor will not be known as throughout deserialization, and the category will not be loaded once more, its worth stays “Adidas”. It might have been null if de-serialization would have taken place at one other JVM occasion.

Now let’s examine our three occasion variables _id, _size, and _color, their values are persevered throughout serialization and are restored throughout de-serialization. This is the reason we see right values for these three fields. Subsequent is our transient variable isRunningShoe, it is a tough one, the worth of a transient variable will not be saved throughout Serialization and that is why the worth of isRunningShoe is inaccurate after de-serialization.

It was true earlier than however it turned false after de-serialization. You wouldn’t have observed this had that boolean variable was initialized as false, and you’ll have thought that the worth of the transient variable was saved and restored, which isn’t true. So watch out for default values throughout Serialization, variables like static and transient will likely be initialized to their default worth after de-serialization.

Final is our non-serializable occasion variable _thread, which holds the occasion of java.lang.Thread, which does not implement the Serializable interface. It is actually fascinating that the default Serialization course of would not complain about this variable, this can be tough to know if do not pay sufficient consideration. The rationale was that the variable did not maintain any worth.

Now simply initialize that variable as Thread _thread = new Thread() and re-run this system once more. This time will get the next Exception :

Exception in thread "predominant" java.lang.Thread
 at Supply)
 at Supply)
 at Supply)
 at Supply)
 at Supply)
 at Supply)
 at SerializationDemo.writeShoe(
 at SerializationDemo.predominant(

As a result of Thread would not implement a Serializable interface, you can’t serialize it. This can be a quite common downside throughout the upkeep of a legacy Java venture. Suppose you may have a Serializable class Worker, and later one developer launched one other occasion variable Division, which isn’t Serializable. Are you aware what’s going to occur? The Worker cannot be serialized anymore.

That is why I like to recommend placing a Serialization alert within the supply file of a Serializable class, reminding them about not including any variable which isn’t serializable or making it transient in the event that they really want it. You’ll be able to additional see Java Coding Pointers for extra coding finest practices whereas writing Java functions. It incorporates 75 suggestions for dependable and safe Java packages.

Briefly, we will say that :

  • The worth of the static variable will not be persevered throughout Serialization.
  • The transient variables will not be persevered as properly.
  • Any NonSerializable discipline, which isn’t static or transient will break the Serialization course of by throwing
  • The constructor of a serializable class will not be known as throughout Serialization.

That is all about learn how to serialize an object in Java utilizing a Serializable interface. We’ve seen each saving and restoring objects utilizing serialization and de-serialization and likewise explored some key ideas associated to how serialization works in Java.

 For instance, transient and static variables will not be saved throughout serialization, if you happen to declare a static variable, ensure that it isn’t ultimate, and keep in mind that constructor will not be known as throughout the de-serialization course of.

All these ideas are crucial to implement serialization appropriately in your program. You’ll be able to additional learn Efficient Java by Joshua Bloch to know efficient serialization e.g. with customized binary codecs.  All of the gadgets associated to Serialization on this guide are a must-read for any critical Java developer.

Different Java serialization tutorials you might prefer to discover

  • What Each Java developer ought to find out about Serialization (learn)
  • Distinction between Serializable and Externalizable in Java? (reply)
  • Why must you use SerialVersionUID in Java? (reply)
  • Google Protocol Buffer – a quick different of serialization in Java? (tutorial)
  • Distinction between transient and risky variables in Java? (reply)
  • Find out how to use a transient variable within the Serializable class? (reply)

Thanks for studying this text thus far. In the event you like this Java Serialization tutorial land clarification then please share it with your pals dn colleagues. When you have any questions or suggestions please drop a notice. 



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments