Skip to content
Related Articles

Related Articles

Java Program to Convert Byte Array to Object

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 02 Feb, 2022

Converting byte array into Object and Object into a byte array process is known as deserializing and serializing. The class object which gets serialized/deserialized must implement the interface Serializable.

  • Serializable is a marker interface that comes under package ‘java.io.Serializable’.
  • Byte Array: Byte Array is only used to store byte data type values. The default value of the elements in a byte array is 0.
  • Object: User-defined data type.

For serialized/deserialized, we use class SerializationUtils.

Approach (Using SerializationUtils class)

  • Serializing and deserializing are two main functions of this class.
  • This class comes under package ‘org.apache.commons.lang3‘.

Serializing (converting Object into a byte array)

Syntax: 

public static byte[] serialize(Serializable object)

Parameter: An object that the user wants to serialize.

Returns: Function will return byte array.

Deserializing (converting byte array into Object)

Syntax:  

public static Object deserialize(byte[] objectByteArray)

Parameter: Serialized Byte Array.

Returns: Function will return Object.

Example:

Java




// Java Program to Convert Byte Array to Object
import java.io.*;
import org.apache.commons.lang3.*;
  
class gfgStudent implements Serializable {
    public int rollNumber;
    public String name;
    public char gender;
  
    public gfgStudent(int rollNumber, String name,
                      char gender)
    {
        this.rollNumber = rollNumber;
        this.name = name;
        this.gender = gender;
    }
}
  
class gfgMain {
    public static void main(String arg[])
    {
        gfgStudent student;
        student = new gfgStudent(101, "Harsh", 'M');
  
        // converting Object to byte array
        // serializing the object of gfgStudent class
        // (student)
        byte byteArray[]
            = SerializationUtils.serialize(student);
  
        gfgStudent newStudent;
  
        // converting byte array to object
        // deserializing the object of gfgStudent class
        // (student) the function will return object of
        // Object type (here we are type casting it into
        // gfgStudent)
        newStudent
            = (gfgStudent)SerializationUtils.deserialize(
                byteArray);
  
        System.out.println("Deserialized object");
        System.out.println(newStudent.rollNumber);
        System.out.println(newStudent.name);
        System.out.println(newStudent.gender);
    }
}


Output :


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!