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.lang.Object;

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)) {
        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);

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


Happy coding!