×

Java Externalization

What is Externalization in Java?

Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine ) to another JVM through a network. Serialization in Java is not efficient. In serialization, we have no control over how the object is created or over object properties. If we have objects like bloated objects that are objects with too many attributes and a lot of properties serialization is not good practice. Here externalization comes in handy.

Externalizable Interface

In serialization, we have no control over how the object is created or over object properties. This means whatever properties we defined those object properties will be returned to that file, and we can get complete output when we deserialize. Suppose we want to control only one or few properties then we should implement an externalizable interface. An externalizable interface is present in the "java.io" package. Here the object's class should be implemented in the interface " java.io.Externalizable ".

The externalizable interface provides two methods:

  • readExternal()
  • writeExternal()

readExternal() method in Externalizable interface :

The readExternal() method implements the externalizable interfaces object. By calling the methods of Data Input for primitive types it restores the objects. For objects, strings, and arrays datatypes it can readObjects.

Let’s understand the implementation of the readExternal() method in an externalizable interface :

readExternal() method shows the following rules :

To take object input, we should pass an object in the readExternal() method.

For primitive datatypes, we can use methods like readBoolean(), readInt(), readByte() etc…

We can use the readObject() method for strings, arrays, and any custom classes.

Let‘s understand briefly about the readExternal() method using the program :

public void readExternal(ObjectInput in) throws ClassNotFoundException, IOException {  
this.code1 = in.readInt();  // reads integer
this.name1 = (String) in.readObject();  // reads string
this.password1 = (String) in.readObject();  
this.birthday1 = (Date) in.readObject();  
}  

Here, the readInt() method is used to deserialize the code1, and the readObject() method is used to deserialize the name1, password1, and birthday1.

writeExternal() method in Externalizable interface :

First of all, this method is used to save the contents. The contents of primitive datatypes are saved by calling the methods of data outputs. For string, arrays, and for objects writeObject() method is called.

Let us understand briefly.

writeExternal() method shows the following rules :

  • writeBoolean(), writeInt(), writeByte(), writeFloat() etc… methods are used for primitive datatypes.
  • WriteObject() method is used for arrays, strings, and custom classes.

Let us understand the writeExternal() method by considering the following snippet.

public void writeExternal(ObjectOutput out) throws IOException {  
out.writeInt(code1);  
out.writeObject(name1);  
out.writeObject("");  
out.writeObject(birthday1);  
}  

From the above program, the writeObject() method is used to serialize the name1, password1, and birthday1.

To serialize the code, we have used writeInt() method.

Let us understand externalization using the program.

Tester.java

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;


public class Tester {
   public static void main(String[] args) {


      Employee1 e = new Employee1();
      e.name1 = "JavaTpoint";
      e.age1 = 30;
      try (
         FileOutputStream fileOut = new FileOutputStream("test.txt");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
      ) {
         out.writeObject(e);
      }catch (IOException i) {
         System.out.println(i.getMessage());
      }
      try (
         FileInputStream fileIn = new FileInputStream("test.txt");
         ObjectInputStream in = new ObjectInputStream(fileIn);
      ) {
         e = (Employee1)in.readObject();
         System.out.println(e.name1);
         System.out.println(e.age1);
      } catch (IOException i) {
         System.out.println(i.getMessage());
      } catch (ClassNotFoundException e1) {
         System.out.println(e1.getMessage());
      }
   }
}


class Employee1 implements Externalizable {
   public Employee1(){}
   String name1;
   int age1;
   public void writeExternal(ObjectOutput out) throws IOException {
      out.writeObject(name1);
      out.writeInt(age1);
   }
   public void readExternal(ObjectInput in) throws ClassNotFoundException,
   IOException {
      name1 = (String)in.readObject();
      age1 = in.readInt();
   }
}

Output :

Externalization in Java

Difference between serialization and externalization

Serialization vs Externalization

KeySerializationExternalization
InterfaceIt is a marker interface.Externalizable interface provides two methods they are readExternal() and writeExternal().
UIDIt needs SerialversionUID.No UID is used.
StorageIn serialization, If the data have an object then it can be stored.In Externalization, we can store the object directly.
AccessThere is no such access.Complete control of serialization process to application. Is done through externalizable interface.
ProcessThis is a default serialization.This is a custom serialization.
PerformanceIt provides relatively slow performance.For implementation approach, it provides full control.

Related Topics

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.