Convert an object to byte in Java

In this tutorial, you will learn how to convert an object to byte in Java.

More like this:

To begin with, the following namespaces are needed for the code to run properly.

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.Object;
import java.io.IOException;

Convert an object to byte using Java

The function below takes an object as an argument and returns its value in Bytes:

public static byte[] ConvertObjToBytes(Object object) 
{
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
        objectOutputStream.writeObject(object);
        return byteArrayOutputStream.toByteArray();
    } catch (IOException ex) {
  System.out.println("Exception thrown  :" + ex);
    }
    throw new RuntimeException();
}

Now you can run the program from the main method:

public static void main(String[] args)
{
    Object obj;
    obj = "Hello world";
    byte[] b =   ConvertObjToBytes(obj);
    System.out.println(b);
    
}

Run the program, and the output should print as the following:

Output
[B@5d3411d

Happy coding!