Difference Between Serializable and Externalizable in Java Serialization
Last Updated :
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
import java.io.*;
import java.util.*;
class serializableDemo implements Serializable {
String name;
int age;
int jobId;
public serializableDemo(String name, int age, int jobId)
{
this.name = name;
this.age = age;
this.jobId = jobId;
}
public static void main(String[] args) throws Exception
{
serializableDemo t1
= new serializableDemo("Ram", 34, 2364);
FileOutputStream fos
= new FileOutputStream("abc1.ser");
ObjectOutputStream oos
= new ObjectOutputStream(fos);
oos.writeObject(t1);
System.out.println("Object has been serialized");
FileInputStream fis
= new FileInputStream("abc1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
serializableDemo t2
= (serializableDemo)ois.readObject();
System.out.println("Object has been deserialized ");
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
Externalizable
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
import java.io.*;
import java.util.*;
public class ExternalizableDemo implements Externalizable {
String name;
int age;
int jobId;
public ExternalizableDemo()
{
System.out.println(
"Public no-argument constructor");
}
public ExternalizableDemo(String name, int age,
int jobId)
{
this.name = name;
this.age = age;
this.jobId = jobId;
}
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeObject(name);
out.writeInt(age);
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
name = (String)in.readObject();
age = in.readInt();
}
public static void main(String[] args) throws Exception
{
ExternalizableDemo t1 = new ExternalizableDemo("Ram", 35, 23675);
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(t1);
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
ExternalizableDemo t2 = (ExternalizableDemo)ois.readObject();
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.
Serializable
Externalizable
A serializable interface is used to implement serialization.
An externalizable interface used to implement Externalization
Serializable is a marker interface i.e. it does not contain any method.
The externalizable interface is not a marker interface and thus it defines two methods writeExternal() and readExternal() .
Serializable interface passes the responsibility of serialization to JVM and the programmer has no control over serialization, and it is a default algorithm.
The externalizable interface provides all serialization responsibilities to a programmer and hence JVM has no control over serialization.
Serialization using a serializable interface has bad performance.
Serialization using an externalizable interface has better performance.
Default serialization does not require any no-arg constructor.
A public no-arg constructor is required while using an Externalizable interface.
It is hard to analyze and modify class structure because any change in structure may break serialization.
It is relatively easy to analyze and modify class structure because of complete control over serialization logic.
Using a serializable interface we save the total object to a file, and it is not possible to save part of the object.
Base on our requirements we can save either the total object or part of the object.
Transient keywords play an important role here.
Transient keywords won’t play any role.
Similar Reads
Difference Between Serializable and Externalizable in Java Serialization
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 se
6 min read
Difference between External link and Internal link
1. Internal Link : Internal links are hyperlinks that direct the readers to a target page on your website. Internal link is a link from one page to another page on the same domain. Example are website navigation. Advantages of good internal link are : Internal link improves usability through anchor
2 min read
Difference Between Serializable and Parcelable in Android
Android is a mobile operating system developed by Google and it is used by millions of people all over the world. Android is open-source software and is widely popular for its user-friendly interface and flexibility. The Android platform supports two different ways of transferring data between activ
2 min read
Difference Between List and Set in Java
The List interface allows storing the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values are allowed to store. List preserves the insertion order, it allows positional access and insertion of elements. Declaration: public abstr
2 min read
Difference between Javabeans and Enterprise Javabeans
Notejava.beans: This package has been deprecated in Java 9 and later versions, in favor of using annotations and other modern ways of creating beans. Using it in production code is not recomended.JavaBeans: JavaBeans are recyclable software components for Java which by using a builder tool can be ma
2 min read
Difference between List, Set and Map in Java
List interface in Java is a sub-interface of the Java collections interface. It contains the index-based methods to insert, update, delete, and search the elements. It can have duplicate elements also. We can also store the null elements in the list. List preserves the insertion order, it allows pos
4 min read
Difference between volatile and transient keywords in Java
Just like any other programming language, Java has a set of keywords which are reserved and have a special meaning. In this article, we will see the difference between the keywords volatile and transient. Before getting into the differences, let us first understand what each of them actually means.
3 min read
Difference between Java IO and Java NIO
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API's. In this
3 min read
Difference Between java.lang and java.util
Java Packages contain classes, interfaces, and sub-packages. The packages java.lang and java.util are two of the most commonly used packages in Java Standard Library. Both packages contain useful classes and utilities. In this article, we will learn about java.lang and java.util package with example
2 min read
Difference Between fields and read_only_fields in ModelSerializer
In Django REST Framework (DRF), ModelSerializer simplifies creating API endpoints by automatically mapping our model's fields to the API. You can customize the data shown with two important attributes: fields, which define which fields to include, and read_only_fields, which ensures certain fields c
2 min read