Sobes.tech
Junior — Middle

Explain the mechanism of converting Java objects to byte streams and back.

sobes.tech AI

Answer from AI

In Java, the process of converting objects into a byte stream is called serialization, and the reverse process is called deserialization.

Serialization:

  • The object is converted into a sequence of bytes that can be saved to a file, transmitted over a network, etc.
  • The class of the object must implement the Serializable interface.
  • The ObjectOutputStream class is used to write the object to the stream.

Deserialization:

  • The byte stream is converted back into an object.
  • The ObjectInputStream class is used to read the object from the stream.

Example:

import java.io.*;

class Person implements Serializable {
    String name;
    int age;

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

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

// Deserialization
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
    Person p2 = (Person) ois.readObject();
}

Thus, serialization allows saving the state of an object, and deserialization restores it from the saved data.

Explain the mechanism of converting Java objects to… - sobes.tech