Sobes.tech
Junior — Middle

Could you explain what it means to transform an object into a data stream for storage or transmission?

sobes.tech AI

Answer from AI

The process of converting an object into a data stream is called serialization. It is necessary to save the state of an object to a file, database, or transmit it over a network. During serialization, the object is transformed into a sequence of bytes, which can then be restored (deserialized) back into an object.

In Java, for this, the class must implement the Serializable interface. Example:

import java.io.*;

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

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

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User user = new User("Ivan", 30);

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

        // Deserialization
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.dat"))) {
            User restoredUser = (User) ois.readObject();
            System.out.println(restoredUser.name + ", " + restoredUser.age);
        }
    }
}

Thus, serialization allows saving or transmitting an object in a convenient format.

Could you explain what it means to transform an… - sobes.tech