Difference Between Serializable and Externalizable in Java Serialization

02 Mar, 2022
The process of writing the state of an object to a file is called serialization, but strictly speaking, it is the process of converting an object from java supported form into a file-supported form or network-supported form by using fileOutputStream and objectOutputStream classes we can implement serialization. 
But we can serialize only serializable objects. An object is said to be serializable if and only if the corresponding class implements a Serializable interface. Serializable interface is present in java.io package, and it doesn’t contain any method and hence it is a marker interface. If we are trying to serializable a non-serializable object then we will get Runtime Exception saying notSerializableException. 
Example:
Java
// Java Program to illustrate Serializable // Importing utility classes// Importing input output classesimport java.io.*;import java.util.*; // Main Class// Class implementing serializable interfaceclass serializableDemo implements Serializable {         // Member variables of this class    String name;    int age;    int jobId;     // Default constructor    public serializableDemo(String name, int age, int jobId)    {        // This keyword is used to refer        // current object instance        this.name = name;        this.age = age;        this.jobId = jobId;    }     // Method 2    // Main driver method    public static void main(String[] args) throws Exception    {         // Creating an object of class in main() method        serializableDemo t1            = new serializableDemo("Ram", 34, 2364);         // Serialization         // Saving of object in a file        FileOutputStream fos            = new FileOutputStream("abc1.ser");        ObjectOutputStream oos            = new ObjectOutputStream(fos);         // Method for serialization of object        oos.writeObject(t1);         System.out.println("Object has been serialized");        // Deserialization         // Reading the object from a file        FileInputStream fis            = new FileInputStream("abc1.ser");        ObjectInputStream ois = new ObjectInputStream(fis);         // Method for deserialization of object        serializableDemo t2            = (serializableDemo)ois.readObject();         // Display message only        System.out.println("Object has been deserialized ");         // Print and display the name and age        // to illustrate Serializable        System.out.println("Name:" + t2.name + "\n"                           + "Age:" + t2.age + "\n"                           + t2.jobId);    }}
Output:
Object has been serialized
Object has been deserialized  
Name:Ram
Age:34  
2364  
In serialization, everything is taken care of by JVM and the programmer doesn’t have any control. In serialization, it is always possible to solve the total object to file, and it is not possible to save part of the object which may create performance problems. To overcome this problem we should go for externalization.
The main advantage of Externalizable over serialization is, everything is taken care of by the programmer and JVM doesn’t have any control. Based on our requirements we can save either the total object or part of the object which improves the performance of the system. To provide the generalizable ability for any java object, it’s a mandate for the corresponding class to implement a generalizable interface.
This interface defines two methods as follows:
Method 1 
public void  writeExternal( ObjectOutput obj ) throws IOException
This method will be executed automatically at the time of serialization within this method we have to write code to save the required variable to the file.
Method 2         
public void  readExternal(ObjectInput  in )throws IOException , ClassNotFoundException
This method will be executed automatically at the time of deserialization. Within this method, we have to write code to read the required variable from the file and assign it to the current object. But strictly speaking at the time of deserialization JVM will create a separate new object by executing a public no-argument constructor and then on that object, JVM will call the readExternal method.
Hence, every Externalizable implemented class should compulsorily contain a public no-argument constructor otherwise we will get Runtime Exception saying InvalidClassException.
Example:
Java
// Java Program to illustrate Externalizable // Importing input output classesimport java.io.*;// Importing utility classesimport java.util.*; // Main Class// Class implementing externalizable classpublic class ExternalizableDemo implements Externalizable {     // Member variables of this class    String name;    int age;    int jobId;     // Constructors of this class     // Constructor 1    // No-argument constructor    public ExternalizableDemo()    {         // Display message        System.out.println(            "Public no-argument constructor");    }     // Constructor 2    // Default constructor    public ExternalizableDemo(String name, int age,                              int jobId)    {         // This keyword refers to current object itself        this.name = name;        this.age = age;        this.jobId = jobId;    }     // Implementing write external method    public void writeExternal(ObjectOutput out)        throws IOException    {        // Writing name and age to file        out.writeObject(name);        out.writeInt(age);    }     // Implementing readExternal method    public void readExternal(ObjectInput in)        throws IOException, ClassNotFoundException    {        // Reading name from file        name = (String)in.readObject();         // Reading age from file        age = in.readInt();    }     // Main method    public static void main(String[] args) throws Exception    {         // Creating an object of type ExternalizableDemo        ExternalizableDemo t1 = new ExternalizableDemo("Ram", 35, 23675);         // Serialization of object        FileOutputStream fos = new FileOutputStream("abc.ser");         ObjectOutputStream oos = new ObjectOutputStream(fos);         oos.writeObject(t1);         // Deserialization        FileInputStream fis = new FileInputStream("abc.ser");         ObjectInputStream ois = new ObjectInputStream(fis);         ExternalizableDemo t2 = (ExternalizableDemo)ois.readObject();         // Display message        System.out.println("Name :"                           + " " + t2.name + " "                           + "Age :"                           + " " + t2.age);    }}
 Output: 
Public no-argument constructor
Name : Ram Age : 35
Now, we are done discussing both of them, let us conclude all the differences in a table for a better reach of understanding.
anikaseth98
avinashsatpathy07
popliparul20
avtarkumar719
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.