Open In App

How to Efficiently Serialize and Deserialize Arrays in Java?

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Serialization is the process of converting an object into a byte stream and deserialization is the process of reconstructing the object from that byte stream. When working with the arrays in Java, efficiently serializing and deserializing them is essential for data storage and transfer.

Prerequisites:

Program for Serialize and Deserialize Arrays in Java

Below is the implementation of the Serialize and Deserialize Arrays in Java:

Java




// Java Program to Serialize 
// And Deserialize Arrays
import java.io.*;
  
// Driver Class
public class GFG {
      // Main Function
    public static void main(String[] args) {
        int[] intArray = {10, 20, 30, 40, 50};
          
          // Serialization
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("array.ser"))) {
            out.writeObject(intArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
        // Deserialization
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("array.ser"))) {
            int[] deserializedArray = (int[]) in.readObject();
            for (int num : deserializedArray) {
                System.out.print(num + " ");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


Output :

10 20 30 40 50

Explaination of the above Program:

The Program is divided into two parts Serialization and Deserialization.

Sertialization:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("array.ser"))

Here the created byte stream is stored in out variable is intialised with “array.ser” being the file where array is written. Then next step is ,

out.writeObject(intArray);

Here the “array.ser” is filled with the content of intArray.

Deserialization:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("array.ser"))

Here in is used to read “array.ser” . After which,

int[] deserializedArray = (int[]) in.readObject();

It is just extracting data from file and then filling the array elements.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads