Sobes.tech
Junior — Middle

Can you explain what is meant by transforming objects into a data stream for storage or transmission?

sobes.tech AI

Answer from AI

The process of converting objects into a data stream for storage or transmission is called serialization.

Serialization allows an object to be represented as a sequence of bytes, which can be saved to a file, database, or transmitted over a network. Later, these bytes can be converted back into an object — this is called deserialization.

In Java, for serialization, a class must implement the Serializable interface:

import java.io.*;

public class User implements Serializable {
    private String name;
    private int age;

    // constructors, getters, setters
}

// Serialization
User user = new User("Ivan", 30);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.dat"))) {
    oos.writeObject(user);
}

// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"))) {
    User deserializedUser = (User) ois.readObject();
}

Thus, serialization facilitates saving the state of objects and exchanging them between systems.