Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Convert an object to byte in Java

Tags: object java byte

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

More like this:

  • Get System Date and Time in Java
  • Print Prime Numbers from 1 to N in Java
  • Program to get yesterday’s date in Java

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 return 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, the output should print as the following:

Output
[B@5d3411d

Happy coding!



This post first appeared on Php Convert Array To String, please read the originial post: here

Share the post

Convert an object to byte in Java

×

Subscribe to Php Convert Array To String

Get updates delivered right to your inbox!

Thank you for your subscription

×