×

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

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

How to add 24 Hours to Date in Java?

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

2 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.