Serialization is used to convert an object’s state into a format that can be easily stored or transmitted, such as a string. In this article, we will see how to serialize an object into a string with Java’s built-in serialization mechanism.

Serializing an Object into a String:

To serialize an object into a string, you can use the ObjectOutputStream class along with a ByteArrayOutputStream. Following is the step-by-step process of how you can do it.

Let us first get started by importing the required classes.


Create a class to serialize

class Person implements Serializable {
    String name;
    int age;

    public Person(String name, int age) { = name;
        this.age = age;

Create an object and serialize it into a string

public class ObjectToStringSerialization {

    public static String serializeToString(Object object) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            return bos.toString();
        } catch (Exception e) {
            return null;

    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        String serializedString = serializeToString(person);
        System.out.println("Serialized String: " + serializedString);


In the above example, we define a Person class that implements the Serializable interface. This interface is a marker interface that indicates the class can be serialized.

The serializeToString() method takes an object and uses an ObjectOutputStream to serialize it into a ByteArrayOutputStream. The byte stream is then converted to a string using the toString() method of the byte array output stream.

In the main() method, we create a Person object, serialize it into a string using serializeToString(), and finally display the serialized string.


Categorized in:

Tagged in: