×

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

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

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 Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.