×

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

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

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

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.