What is Serialization and Deserialization in Java ?

What is Serialization and Deserialization in Java ?

what is serialization ? how it is done in spring framework project ?

  1. process of converting object into bytes so that we can save it or transit it

  2. once the object is serialized it can be store in a file, database or memory , file can be any type of file , Database you know sql or no sql and memory means some kind of cache , why we wants to store out object, we wants to store our object since the objects are available in heap memory and this memory is dynamic this object can be defrenced and once it is done the data of the object will be lost, but we wants to persist this data that's why that object are stored somewhere

  3. with serialization we can transfer objects

    1. aplication to application via REST API
    2. throuhg firewall JSON or XML
    3. Across Domains
    4. to other data stores :
    5. to identify changes in data over time
  4. Example of serialization in java

// Java code for serialization and deserialization
// of a Java object
import java.io.*;

class Demo implements java.io.Serializable
{
    public int a;
    public String b;

    // Default constructor
    public Demo(int a, String b)
    {
        this.a = a;
        this.b = b;
    }

}

class Test
{
    public static void main(String[] args)
    {
        Demo object = new Demo(1, "geeksforgeeks");
        String filename = "file.ser";

        // Serialization
        try
        {
            //Saving of object in a file
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);

            // Method for serialization of object
            out.writeObject(object);

            out.close();
            file.close();

            System.out.println("Object has been serialized");

        }

        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }


        Demo object1 = null;

        // Deserialization
        try
        {
            // Reading the object from a file
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);

            // Method for deserialization of object
            object1 = (Demo)in.readObject();

            in.close();
            file.close();

            System.out.println("Object has been deserialized ");
            System.out.println("a = " + object1.a);
            System.out.println("b = " + object1.b);
        }

        catch(IOException ex)
        {
            System.out.println("IOException is caught");
        }

        catch(ClassNotFoundException ex)
        {
            System.out.println("ClassNotFoundException is caught");
        }

    }
}