×

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

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes 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.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 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.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 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 Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.