Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconWhat Is Externalization In Java? Interface, Features & Example

What Is Externalization In Java? Interface, Features & Example

Last updated:
26th Jun, 2023
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
What Is Externalization In Java? Interface, Features & Example

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 

What are Serialisation and Externalisation?

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.

Ads of upGrad blog

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

Explore Our Software Development Free Courses

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

Difference Between Serialization and Externalization In Java

BasisExternalization In JavaSerialization in Java
ProcessCustom serializationDefault serialization
StorageStores objects directlyStores only those data with objects
UIDNot availableserialVersionUID
InterfaceComprises two methods: writeExternal() and readExternal()Marker interface
PerformanceOffers full control and authority over the implementation processOffers relatively slow performance 

Externalization In Java: When Do You Use It?

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 Externalisable Interface

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.

Externalizable Interface Methods: An Overview

void readExternalvoid writeExternal
Also known as ObjectInput inStream.Also known as ObjectOutput outStream.
  • The readExternal() function calls several methods on the supplied ObjectInput to retrieve the contents of the caller object. 
  • To put it another way, when we wish to read fields off a stream into an object, we utilize the readExternal() method. 
  • The readExternal() method’s logic for reading an object’s fields must be written. 
  • By executing several methods on the designated ObjectOutput outStream, the writeExternal() method saves the contents of the caller object. 
  • To put it simply, we utilize the writeExternal() method to write an object’s fields to a stream. 
  • Inside the writeExternal() method, write the logic for writing data fields. 
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.

}

  • The byte stream from which the item is to be read is designated as inStream in this procedure. 
  • ObjectInputStream implements ObjectInput, a sub-interface of DataInput. 
  • The byte stream outStream specifies the object’s intended destination. 
  • Implemented by ObjectOutputStream, ObjectOutput is a sub-interface of DataOutput. 

Additional Notes On void readExternal() Method:

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.

Explore our Popular Software Engineering Courses

Features

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 

Example 

// 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();
 }
}

In-Demand Software Development Skills

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.

Ads of upGrad blog

Read our Popular Articles related to Software Development

Conclusion

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are interfaces in Java?

An interface is one of the types in java which doesn't have any implementation and it is just a group of method signature. This interface can't be created. The reason behind this fact is that these interfaces are just a collection of method signatures. Once we create an interface, we can't keep on adding new method in it. For example, we can't add a method in java.Aspect interface which will help us in modifying the class behavior from outside the class. As this goes against the object-oriented programming principle. In reality interfaces are nothing but java annotations extension. We should use interfaces to keep our code light.

2What is externalization in Java?

Externalization is the ability of an object to make its state mutable. Externalization is used in design patterns like Singleton, Factory and Prototype to implement the dependency inversion principle and the Interface Segregation Principle. Externalization is not a built-in feature of Java, but it is possible to add that feature to a class. Externalization is a process of converting an object into a character stream in Java. It is a mechanism that is used for storing objects in files in a binary format. It is used for storage of character data in files as a sequence of bytes. The data can be read in subsequent executions of the Java program.

3What are the features of java programming language?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. Multiple updates have been released since then, with the latest version being Java 11. Java was intended to run on any platform that can support the Java virtual machine, hence it is also a programming platform. It can run in an environment with just a browser, but it's most commonly used with various versions of the Java Virtual Machine (JVM) under sets of programs called application programming interfaces or APIs.