What Is Externalization In Java? Interface, Features & Example
Updated on Jul 03, 2023 | 8 min read | 7.8k views
Share:
For working professionals
For fresh graduates
More
Updated on Jul 03, 2023 | 8 min read | 7.8k views
Share:
Table of Contents
To answer what is externalization In java, we can say it is a common mechanism that is implemented to customize serialization. It is used with the main aspect that the java serialization is not that efficient, so an external customization parameter is used when there are bloated objects that hold multiple properties and attributes.
Check out our free courses to get an edge over the competition
Serialization- It is the mechanism used to compose data of an object into a byte-stream, the process is mainly implemented in RMI, JMS, JPA type of technologies. The other type consists of a mechanism that reverses the function and process of serialization and termed deserialization. The function of serialization as the name depicts is to serialize the objects present in java.
Externalisation- It is defined as the mechanism used to customize the serialization mechanism. The bloatware is not fast and responsive. It generates the need for a good mechanism that is efficient and responsive enough to customize the whole process.
In serialization, the java programming machine responds to the process of writing and reading objects. This is a much-used case scenario as the programmers get levied of the need to worry about the serialization process. In such cases, the default working serialization does not intend to save important credentials like the login ID and the passwords.
Check out upGrad’s Advanced Certification in DevOps
But, if the programmers find the need to secure the same credentials, externalization proves its purpose to give the full control over the handling of the data of the reading and writing object of the data during serialization.
Checkout: Popular Java Frameworks
Basis | Externalization In Java | Serialization in Java |
Process | Custom serialization | Default serialization |
Storage | Stores objects directly | Stores only those data with objects |
UID | Not available | serialVersionUID |
Interface | Comprises two methods: writeExternal() and readExternal() | Marker interface |
Performance | Offers full control and authority over the implementation process | Offers relatively slow performance |
Externalization in Java is the ideal choice when only a portion of an object needs to be serialized. Besides knowing ‘what is externalization in Java,’ remember that only the fields that are necessary for an object must be serialized.
The interface is implemented when there is a requirement to moderate reading and writing the objects during serialization and deserialization. Thus the need for an object class with the java.io.externalisable interface, helps users and programmers implement their customized code on the objects states by writing in the writeExternal() and read objects in the readExternal() method.
For better ideation let us understand both the methods
Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)
readExternal() works when an object takes the input. The contents are restored to the original context by the methods of data Input by calling the write Object method for objects, strings, and arrays.
writeExternal() works when an object takes the input, and the methods of data output save the contents by calling the read Object method for objects, strings, and arrays.
void readExternal | void writeExternal |
Also known as ObjectInput inStream. | Also known as ObjectOutput outStream. |
|
|
The readExternal() function can be declared in general using the following syntax with the supplied object input stream: public void readExternal(ObjectInput inStream) throws IOException, ClassNotFoundException { // Here, write the logic to read an object’s fields from the stream. } |
The writeExternal() function can be declared using the generic syntax shown below with the provided object output stream: public void writeExternal(ObjectOutput outStream) throws IOException { // Here, write the logic to write object fields to a stream. } |
|
|
For primitive data types, one can leverage the readLong(), readInt(), readByte(), and readBoolean() methods. For custom classes, like String or Arrays, use the readObject() method. An IOException is thrown by the readExternal() method in the event of an I/O error. A ClassNotException will be thrown in the event that the class of the object being restored cannot be found.
Externalization helps to implement the logic control to the application by bypassing the read External and write External methods.
Externalisation proved an effective way for the programmers as they were enabled to create code with their conscience and logic to eliminate the variables during the java object’s externalizing.
Externalization methods give complete manual control over the implementation approach, and the object serialization and the inheritance can be implied as well.
Also Read: Java Interview Questions
// interface
import java.io.*;
class Car implements Externalizable {
static int age;
String name;
int year;
public Car()
{
System.out.println("Default Constructor called");
}
Car(String n, int y)
{
this.name = n;
this.year = y;
age = 10;
}
@Override
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeObject(name);
out.writeInt(age);
out.writeInt(year);
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
name = (String)in.readObject();
year = in.readInt();
age = in.readInt();
}
@Override public String toString()
{
return ("Name: " + name + "\n"
+ "Year: " + year + "\n"
+ "Age: " + age);
}
}
public class ExternExample {
public static void main(String[] args)
{
Car car = new Car("Shiney", 1995);
Car newcar = null;
// Serialize the car
try {
FileOutputStream fo
= new FileOutputStream("gfg.txt");
ObjectOutputStream so
= new ObjectOutputStream(fo);
so.writeObject(car);
so.flush();
}
catch (Exception e) {
System.out.println(e);
}
// Deserialize the car
try {
FileInputStream fi
= new FileInputStream("gfg.txt");
ObjectInputStream si
= new ObjectInputStream(fi);
newcar = (Car)si.readObject();
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("The original car is:\n" + car);
System.out.println("The new car is:\n" + newcar);
}
}
Output:
Default Constructor called
The original car is:
Name: Shiney
Year: 1995
Age: 10
The new car is:
Name: Shiney
Year: 1995
Age: 10
Let’s look at a different sort of program where one can serialize some data fields leveraging an Externalizable interface in the writeExternal() approach and deserialize some data fields implementing the readExternal() approach.
package javaProgram;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class Employee implements Externalizable {
String name;
int id;
double salary;
Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
@Override
public void writeExternal(ObjectOutput outStream) throws IOException
{
// Serializing only id and salary.
outStream.writeInt(id);
outStream.writeDouble(salary);
}
@Override
public void readExternal(ObjectInput inStream) throws ClassNotFoundException, IOException
{
// Order of reads must be the same as the order of writes.
id = inStream.readInt();
salary = inStream.readDouble();
}
}
This example is a classic example to depict that when an externalisable object is recreated the instance is triggered with the public no-argument constructor, this tends to summon the readExternal method. So, with the help of an externalisable interface, there would be full control over the java class analogy.
Thus while using externalize it is essential and important that all the field states are in the exact order as they were written.
Also Read: Java Project Ideas & Topics
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
So n being asked about what is externalization in java we can say it weighs importance due to the custom serialization it has to offer and gives full control to customize the serialization and also over the implementation approach. readExternal and writeExternal methods are required to be overwritten by the class. It offers much better performance than serialization.
Connect with upGrad to have a better and deeper understanding of java via the Executive PG Program course on full stack development, to enhance the learning curve you can get started by Rs 10,000 and access the online lectures.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources